numba - 与jit相比,guvectorize非常慢

时间:2015-06-28 15:48:28

标签: python numba

我正在尝试使用Numba的@jit@guvectorize,并发现@guvectorize@jit慢得多。例如,我有以下代码来计算滚动移动平均值:

import numpy as np
from numba import *

@guvectorize(['void(float64[:], float64[:], float64[:])'], '(n),()->(n)')
def sma(x, m, y):
    n = x.shape[0]
    mi = int(m)
    y[:] *= np.nan
    for i in range(mi-1, n):
        for j in range(i-mi+1, i+1):
            y[i] = x[j] if j == i-m+1 else y[i]+x[j]
        y[i] /= double(mi)

@jit(float64[:](float64[:], float64))
def sma1(x, m):
    n = x.shape[0]
    mi = int(m)
    y = np.empty(x.shape[0]) * np.nan
    for i in range(mi-1, n):
        for j in range(i-mi+1, i+1):
            y[i] = x[j] if j == i-m+1 else y[i]+x[j]
        y[i] /= double(mi)
    return y

以下是测试代码:

import movavg_nb as mv1
import numpy as np
x = np.random.random(100)

import time as t

t0 = t.clock()
for i in range(10000):
    y = mv1.sma(x, 5)
print(t.clock()-t0)

t0 = t.clock()
for i in range(10000):
    y = mv1.sma1(x, 5)
print(t.clock()-t0)

我跑了两次,因为Numba通常需要第一次分配类型。以下是第二次测试代码的结果:

17.459737999999998  # corresponding to @guvectorize
0.036977999999997735  # corresponding to @jit

数量级是> 450X

问题:我可以理解@vectorize的目的(输入是相同的),但@guvectorize更快时@jit的目的是什么? (或者我的代码中有什么东西会减慢它?)

0 个答案:

没有答案