gpt4 book ai didi

python - `numpy.sum` 与 `ndarray.sum`

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:37 25 4
gpt4 key购买 nike

对于一维 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

为什么会有差异?这是否意味着我们应该始终使用 numpy.ndarray 版本的函数,例如 summeanstd、等等?

最佳答案

我想这是因为 np.sum() 之类的需要先将输入显式转换为 ndarray(使用 np .asanyarray) checks a few other .sum functions在确定 ndarray.sum 方法之前,以便允许对列表、元组等进行操作

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

关于python - `numpy.sum` 与 `ndarray.sum`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48942424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com