`numpy.sum` 与 `ndarray.sum`

p-v*_*lue 5 python performance numpy

对于一维numpy数组a,我认为np.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
Run Code Online (Sandbox Code Playgroud)

为什么有区别?这是否意味着,我们应该始终使用numpy.ndarray的功能,如版本summeanstd等?

Dan*_*l F 3

我想这是因为np.sum()等等需要显式地将输入转换为ndarray第一个(使用np.asanyarray .sum在确定方法之前检查一些其他函数ndarray.sum,以便允许对列表、元组等进行操作。

另一方面,ndarray.sum()它是类的方法ndarray,因此不需要进行任何检查。