15

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?

gariepy
  • 3,576
  • 6
  • 21
  • 34
  • 2
    It might make more sense to test this with arrays, rather than scalars. That's what numpy is optimized for. – juanchopanza Feb 03 '16 at 17:34
  • 6
    "since I only use the scalar case" - then either your application is completely unsuited for NumPy, or you've implemented your application in a very inefficient manner. NumPy is all about arrays. – user2357112 Feb 03 '16 at 17:38
  • I'd assume it's because math.acos is a builtin function, meant for scalars, whereas numpy ufuncs like np.arccos have overhead relating to dealing with arrays (dispatching based on whether or not the argument is an array) – Gretchen Feb 03 '16 at 17:38
  • If you're doing enough of these operations for their speed to matter, you should probably be using arrays and NumPy whole-array operations instead of `math.whatever`. – user2357112 Feb 03 '16 at 17:41

1 Answers1

12

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

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.

Community
  • 1
  • 1
Florian Rhiem
  • 1,758
  • 1
  • 14
  • 23