如何优化NumPy数组代数的速度?

2024-09-30 06:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

当我将gnuoctave代码转换成Python代码时,我意识到NumPy数组代数比Octave数组代数慢得多。在

特别是在cumprod方法中,存在着巨大的性能差异。(对于以下代码,NumPy大约比倍频程慢80%(倍频程:0.4秒,NumPy:2.0秒)

python

import numpy as np
from timer import Timer

n=1400000
k=30
matrix = np.eye(n, 2*k)
with Timer('speed test'):
    cumprodMatrix = np.cumprod(matrix, axis=0)

倍频程

^{pr2}$

我想让我的Python代码和Octave代码一样高效。有没有更快的方法来计算累积列?在


Tags: 方法代码importnumpynp数组性能matrix
1条回答
网友
1楼 · 发布于 2024-09-30 06:20:32

NumPy代码,如果用Pythran编译,可以更快,这给我们一些启示:

$ cat r.py
import numpy as np
#pythran export r(float[][])
def r(m):
    return np.cumprod(m, axis=0)

$ python -m perf timeit -s 'import numpy as np; n = 1400000; k = 30; matrix = np.eye(n, 2*k); import r' 'r.r(matrix)'
.....................
Median +- std dev: 1.45 sec +- 0.03 sec
$ python -m pythran.run r.py -DUSE_BOOST_SIMD -march=native
$ python -m perf timeit -s 'import numpy as np; n=1400000; k=30; matrix = np.eye(n, 2*k); import r' 'r.r(matrix)'                          .....................
Median +- std dev: 445 ms +- 11 ms

通过将NumPy代码编译为本机代码,这基本上是x3的加速。在

好处来自使用AVX指令,也许Octave也这么做?在

相关问题 更多 >

    热门问题