[英]`numpy.sum` vs. `ndarray.sum`
對於1-D 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
為什么會有區別? 這是否意味着我們應該總是使用sum
, mean
, std
等函數的numpy.ndarray
版本?
我想它是因為np.sum()
之類的東西 需要 在確定ndarray
輸入顯式轉換為ndarray
(使用np.asanyarray
) ndarray.sum
方法之前檢查一些其他.sum
函數 ,以便允許對列表,元組等進行操作。
另一方面, ndarray.sum()
是ndarray
類的一個方法,因此不需要進行任何檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.