簡體   English   中英

`numpy.sum`與`ndarray.sum`

[英]`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

為什么會有區別? 這是否意味着我們應該總是使用summeanstd等函數的numpy.ndarray版本?

我想它是因為np.sum()之類的東西 需要ndarray輸入顯式轉換為ndarray (使用np.asanyarray 在確定ndarray.sum方法之前檢查一些其他.sum函數 ,以便允許對列表,元組等進行操作。

另一方面, ndarray.sum()ndarray類的一個方法,因此不需要進行任何檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM