Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, is math.acos() faster than numpy.arccos() for scalars?

Tags:

python

math

numpy

I'm doing some scientific computing in Python with a lot of geometric calculations, and I ran across a significant difference between using numpy versus the standard math library.

>>> x = timeit.Timer('v = np.arccos(a)', 'import numpy as np; a = 0.6')
>>> x.timeit(100000)
0.15387153439223766
>>> y = timeit.Timer('v = math.acos(a)', 'import math; a = 0.6')
>>> y.timeit(100000)
0.012333301827311516

That's more than a 10x speedup! I'm using numpy for almost all standard math functions, and I just assumed it was optimized and at least as fast as math. For long enough vectors, numpy.arccos() will eventually win vs. looping with math.acos(), but since I only use the scalar case, is there any downside to using math.acos(), math.asin(), math.atan() across the board, instead of the numpy versions?

like image 245
gariepy Avatar asked Feb 03 '16 17:02

gariepy


1 Answers

Using the functions from the math module for scalars is perfectly fine. The numpy.arccos function is likely to be slower due to

  • conversion to an array (and a C data type)
  • C function call overhead
  • conversion of the result back to a python type

If this difference in performance is important for your problem, you should check if you really can't use array operations. As user2357112 said in the comments, arrays are what numpy really is great at.

like image 90
Florian Rhiem Avatar answered Oct 12 '22 09:10

Florian Rhiem