为什么.sum()比.any()或.max()快? [英] Why is .sum() faster than .any() or .max()?
问题描述
优化代码的慢速部分时,我惊讶于A.sum()
几乎是A.max()
的两倍:
When optimising slow parts of my code, I was surprised by the fact that A.sum()
is 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
我曾期望A.any()
会更快(它只需要检查一个元素!),其次是A.max()
,而A.sum()
则是最慢的(sum()
需要加数字和每次更新一个值,max
每次都需要比较数字,有时需要更新,我认为加法应该比比较慢.实际上,情况恰恰相反.为什么?
I had expected that A.any()
would be much faster (it should need to check only one element!), followed by A.max()
, and that A.sum()
would be the slowest (sum()
needs to add numbers and update a value every time, max
needs to compare numbers every time and update sometimes, and I thought adding should be slower than comparing). In fact, it's the opposite. Why?
推荐答案
max
必须存储一个值,连续检查可能的更新(并且CPU需要执行分支操作才能实现这些更新). sum
只会搅动这些值.
max
has to store a value, continuously checking for potential updates (and the CPU needs to do branche operations to effect these). sum
just churns through the values.
所以sum
会更快.
这篇关于为什么.sum()比.any()或.max()快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!