您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何使用numba對Python運(yùn)算加速,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
有時候需要比較大的計算量,這個時候Python的效率就很讓人捉急了,此時可以考慮使用numba 進(jìn)行加速,效果提升明顯~
(numba 安裝貌似很是繁瑣,建議安裝Anaconda,里面自帶安裝好各種常用科學(xué)計算庫)
from numba import jit @jit def t(count=1000): total = 0 for i in range(int(count)): total += i return total
測試效果:
(關(guān)于__wrapped__ 見我的博文: 淺談解除裝飾器作用(python3新增) )
In [17]: %timeit -n 1 t.__wrapped__() 1 loop, best of 3: 52.9 µs per loop In [18]: %timeit -n 1 t() The slowest run took 13.00 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 395 ns per loop
可以看到使用jit 加速后,即使設(shè)置測試一次,實際上還是取了三次的最優(yōu)值,如果取最壞值(因為最優(yōu)值可能是緩存下來的),則耗時為395ns * 13 大概是5us 還是比不使用的52.9us 快上大概10倍,
增大計算量可以看到使用numba加速后的效果提升更加明顯,
In [19]: %timeit -n 10 t.__wrapped__(1e6) 10 loops, best of 3: 76.2 ms per loop In [20]: %timeit -n 1 t(1e6) The slowest run took 8.00 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 790 ns per loop
如果減少計算量,可以看到當(dāng)降到明顯小值時,使用加速后的效果(以最差計)與不加速效果差距不大,因此如果涉及到較大計算量不妨使用jit 加速下,何況使用起來這么簡便。
%timeit -n 1 t(10) 1 loop, best of 3: 0 ns per loop %timeit -n 100 t.__wrapped__(10) 100 loops, best of 3: 1.79 µs per loop %timeit -n 1 t(1) The slowest run took 17.00 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 395 ns per loop %timeit -n 100 t.__wrapped__(1) 100 loops, best of 3: 671 ns per loop
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何使用numba對Python運(yùn)算加速”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。