如果编写函数以利用已numpy
编译的代码(或本身已编译),则很难通过缓存来提高其性能。
In [1]: from scipy.special import gammaln
In [2]: np_array = np.random.randint(5, size=(500))*1000+3
In [3]: np_array.shape
Out[3]: (500,)
In [4]: timeit gammaln(np_array).sum()
....
10000 loops, best of 3: 34.9 µs per loop
评估每个元素会慢得多
In [5]: timeit sum([gammaln(i) for i in np_array])
1000 loops, best of 3: 1.8 ms per loop
简单地遍历数组会更慢。
In [6]: timeit sum([i for i in np_array])
10000 loops, best of 3: 127 µs per loop
在这种情况下,这些值是一小组整数
In [10]: np.unique(np_array)
Out[10]: array([ 3, 1003, 2003, 3003, 4003])
但是识别这些唯一值所花费的时间几乎与计算所有 500 个函数的时间一样长。
In [11]: timeit np.unique(np_array)
...
In [12]: timeit gammaln(np.unique(np_array))
事实上,如果我还要求可以重建数组的索引,它会更慢:
In [14]: timeit np.unique(np_array, return_inverse=True)
10000 loops, best of 3: 54 µs per loop
Python 有缓存或记忆配方,包括@functools.lru_cache
装饰器。但我还没有看到他们太多的numpy
数组。如果您的问题适合缓存,我怀疑最好在较低级别的代码中执行此操作,例如使用 Cython,并使用现有的 C 或 C++ 缓存库。
具有唯一性的缓存
我们可以通过以下方式获得类似缓存的行为unique
- 使用它来获取唯一值和让我们重新创建原始数组的索引:
In [5]: unq, idx=np.unique(np_array, return_inverse=True)
In [6]: res1= gammaln(np_array)
In [7]: res2= gammaln(unq)
In [8]: res2= res2[idx]
In [9]: np.allclose(res1, res2)
Out[9]: True
但是比较一下时间:
In [10]: timeit res1= gammaln(np_array)
10000 loops, best of 3: 29.1 µs per loop
In [11]: %%timeit
...: unq, idx=np.unique(np_array, return_inverse=True)
...: res2= gammaln(unq)[idx]
10000 loops, best of 3: 63.3 µs per loop
大部分额外时间都在计算unique
;一旦我们有了映射,应用它就会非常快:
In [12]: timeit res2=gammaln(unq)[idx]
...
100000 loops, best of 3: 6.12 µs per loop
唯一的总和
返回值的总和而不是实际值会稍微移动相对时间
In [13]: %timeit res1= gammaln(np_array).sum()
10000 loops, best of 3: 35.3 µs per loop
In [14]: %%timeit
...: unq, idx=np.unique(np_array, return_inverse=True)
...: res2= gammaln(unq)[idx].sum()
10000 loops, best of 3: 71.3 µs per loop
使用 Paul Panzer 的计数方法
In [21]: %%timeit
...: unq, cnt=np.unique(np_array, return_counts=True)
...: res=(gammaln(unq)*cnt).sum()
10000 loops, best of 3: 59.5 µs per loop
In [22]: %%timeit
...: unq, cnt=np.unique(np_array, return_counts=True)
...: res=np.dot(gammaln(unq),cnt)
10000 loops, best of 3: 52.1 µs per loop