`numpy.sum` vs.` ndarray.sum`

For the 1-D array, numpy aI thought that np.sum(a)both a.sum()are equivalent functions, but I just did a simple experiment, and it seems that the latter is always a bit faster:

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

Why is there a difference? Does this mean that we should always use the version of the functions numpy.ndarray, such as sum, mean, std, etc.?

+4
source share
1 answer

I would suggest that this is becasue np.sum()and the likeyou must explicitly convert the inputs to ndarrayfirst (using np.asanyarray) .sum ndarray.sum, , ..

, ndarray.sum() ndarray , , .

+2

Source: https://habr.com/ru/post/1694027/


All Articles