【发布时间】:2018-02-23 06:35:59
【问题描述】:
对于一个一维的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 版本?
【问题讨论】:
-
大多数情况下,您会看到一级函数重定向的差异。在大多数情况下,函数版本会将任务重定向到方法(查看代码)。不要担心这里的速度 - 使用使您的代码(对您和您的读者)最清晰的形式。如果您的输入可能是列表而不是数组,则必须使用函数版本。
标签: python performance numpy