1 回答

TA貢獻1807條經(jīng)驗 獲得超9個贊
我做了一個小測試腳本,看看我是否可以重現(xiàn)你的錯誤:
import numba as nb
from IPython import get_ipython
ipython = get_ipython()
@nb.jit(nopython=True)
def f(x):
return (x+1)/x
def fixed_point_for(x):
for _ in range(17):
x = f(x)
return x
@nb.jit(nopython=True)
def fixed_point_for_nb(x):
for _ in range(17):
x = f(x)
return x
def fixed_point_while(x):
error=1
x_old = x
while error>0.01:
x = f(x)
error = abs(x_old-x)
x_old = x
return x
@nb.jit(nopython=True)
def fixed_point_while_nb(x):
error=1
x_old = x
while error>0.01:
x = f(x)
error = abs(x_old-x)
x_old = x
return x
print("for loop without numba:")
ipython.magic("%timeit fixed_point_for(10)")
print("for loop with numba:")
ipython.magic("%timeit fixed_point_for_nb(10)")
print("while loop without numba:")
ipython.magic("%timeit fixed_point_while(10)")
print("for loop with numba:")
ipython.magic("%timeit fixed_point_while_nb(10)")
由于我不了解您的f情況,因此我只使用了我能想到的最簡單的穩(wěn)定功能。然后,我在使用和不numba使用循環(huán)的情況下運行測試。我機器上的結(jié)果是:forwhile
for loop without numba:
3.35 μs ± 8.72 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
for loop with numba:
282 ns ± 1.07 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
while loop without numba:
1.86 μs ± 7.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
for loop with numba:
214 ns ± 1.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
產(chǎn)生以下想法:
不可能,你的函數(shù)是不可優(yōu)化的,因為你的
for
循環(huán)很快(至少你是這么說的;你沒有測試過numba
嗎?)。如您所想,您的函數(shù)可能需要更多的循環(huán)才能收斂
我們使用不同的軟件版本。我的版本是:
numba 0.49.0
numpy 1.18.3
python 3.8.2
添加回答
舉報