使用numba加快循环速度

使用numba加快循环速度,第1张

使用numba加快循环速度

是的,这是Numba真正解决的问题。我更改了您的价值,

dk
因为对于简单的演示而言,这并不明智。这是代码:

import numpy as npimport numba as nbdef f_big(A, k, std_A, std_k, mean_A=10, mean_k=0.2, hh=100):    return ( 1 / (std_A * std_k * 2 * np.pi) ) * A * (hh/50) ** k * np.exp( -1*(k - mean_k)**2 / (2 * std_k **2 ) - (A - mean_A)**2 / (2 * std_A**2))def func():    outer_sum = 0    dk = 0.01 #0.000001    for k in np.arange(dk, 0.4, dk):        inner_sum = 0        for A in np.arange(dk, 20, dk): inner_sum += dk * f_big(A, k, 1e-5, 1e-5)        outer_sum += inner_sum * dk    return outer_sum@nb.jit(nopython=True)def f_big_nb(A, k, std_A, std_k, mean_A=10, mean_k=0.2, hh=100):    return ( 1 / (std_A * std_k * 2 * np.pi) ) * A * (hh/50) ** k * np.exp( -1*(k - mean_k)**2 / (2 * std_k **2 ) - (A - mean_A)**2 / (2 * std_A**2))@nb.jit(nopython=True)def func_nb():    outer_sum = 0    dk = 0.01 #0.000001    X = np.arange(dk, 0.4, dk)    Y = np.arange(dk, 20, dk)    for i in xrange(X.shape[0]):        k = X[i] # faster to do lookup than iterate over an array directly        inner_sum = 0        for j in xrange(Y.shape[0]): A = Y[j] inner_sum += dk * f_big_nb(A, k, 1e-5, 1e-5)        outer_sum += inner_sum * dk    return outer_sum

然后计时

In [7]: np.allclose(func(), func_nb())Out[7]: TrueIn [8]: %timeit func()1 loops, best of 3: 222 ms per loopIn [9]: %timeit func_nb()The slowest run took 419.10 times longer than the fastest. This could mean that an intermediate result is being cached 1000 loops, best of 3: 362 µs per loop

因此,numba版本在我的笔记本电脑上大约快600倍。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5661608.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存