np.sum和np.add.reduce有什么区别? [英] What is the difference between np.sum and np.add.reduce?
问题描述
np.sum
和np.add.reduce
有什么区别?
虽然文档非常明确:
What is the difference between np.sum
and np.add.reduce
?
While the docs are quite explicit:
例如,add.reduce()等同于sum().
For example, add.reduce() is equivalent to sum().
两者的性能似乎完全不同:对于相对较小的数组大小,add.reduce
的速度大约快两倍.
The performance of the two seems to be quite different: for relatively small array sizes add.reduce
is about twice faster.
$ python -mtimeit -s"import numpy as np; a = np.random.rand(100); summ=np.sum" "summ(a)"
100000 loops, best of 3: 2.11 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(100); summ=np.add.reduce" "summ(a)"
1000000 loops, best of 3: 0.81 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(1000); summ=np.sum" "summ(a)"
100000 loops, best of 3: 2.78 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(1000); summ=np.add.reduce" "summ(a)"
1000000 loops, best of 3: 1.5 usec per loop
对于更大的数组大小,差异似乎消失了:
For larger array sizes, the difference seems to go away:
$ python -mtimeit -s"import numpy as np; a = np.random.rand(10000); summ=np.sum" "summ(a)"
100000 loops, best of 3: 10.7 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(10000); summ=np.add.reduce" "summ(a)"
100000 loops, best of 3: 9.2 usec per loop
推荐答案
简短的回答:当参数是一个numpy数组时,np.sum
最终会调用add.reduce
来完成工作.处理参数并分配给add.reduce
的开销是为什么np.sum
较慢的原因.
Short answer: when the argument is a numpy array, np.sum
ultimately calls add.reduce
to do the work. The overhead of handling its argument and dispatching to add.reduce
is why np.sum
is slower.
更长的答案:
np.sum
在 numpy/core/fromnumeric.py
中定义.在np.sum
的定义中,您将
看到工作已传递到_methods._sum
.在 _methods.py
中的该函数很简单:
Longer answer:
np.sum
is defined in numpy/core/fromnumeric.py
. In the definition of np.sum
, you'll
see that the work is passed on to _methods._sum
. That function, in _methods.py
, is simply:
def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
return um.add.reduce(a, axis=axis, dtype=dtype,
out=out, keepdims=keepdims)
um
是定义add
ufunc的模块.
um
is the module where the add
ufunc is defined.
这篇关于np.sum和np.add.reduce有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!