Why is .sum () faster than .any () or .max ()?

When optimizing the slow parts of my code, I was surprised that A.sum() almost twice as fast as A.max() :

 In [1]: A = arange(10*20*30*40).reshape(10, 20, 30, 40) In [2]: %timeit A.max() 1000 loops, best of 3: 216 us per loop In [3]: %timeit A.sum() 10000 loops, best of 3: 119 us per loop In [4]: %timeit A.any() 1000 loops, best of 3: 217 us per loop 

I expected that A.any() would be much faster (you need to check only one element!) And then A.max() and that A.sum() would be the slowest ( sum() you need to add numbers and update the value every time , max you need to compare numbers every time and sometimes update, and I thought adding should be slower than comparison). In fact, the opposite is true. Why?

+7
python numpy
Mar 13 '14 at 10:18
source share
1 answer

max should store the value, constantly checking for possible updates (and to perform these operations, the processor must perform operations with branches). sum simply resets the values.

So, sum will be faster.

+2
Mar 13 '14 at 10:21
source share



All Articles