`numpy.sum`与`ndarray.sum`

时间:2018-02-23 06:36:00

标签: python performance numpy

对于1-D return condition? this.function1(): this.function2(); 数组numpy,我认为anp.sum(a)是等效函数,但我只做了一个简单的实验,似乎后者总是快一点:

a.sum()

为什么会有区别? 这是否意味着我们应该始终使用In [1]: import numpy as np In [2]: a = np.arange(10000) In [3]: %timeit np.sum(a) The slowest run took 16.85 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.46 µs per loop In [4]: %timeit a.sum() The slowest run took 19.80 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 5.25 µs per loop numpy.ndarraysum等函数的mean版本?

1 个答案:

答案 0 :(得分:2)

我认为它是因为np.sum()而类似需要首先将输入显式转换为ndarray(使用np.asanyarray {{ 3}}在确定ndarray.sum方法之前,允许对列表,元组等进行操作。

另一方面,ndarray.sum()ndarray类的一种方法,因此无需进行任何检查。