有時(shí)候需要比較大的計(jì)算量,這個(gè)時(shí)候Python的效率就很讓人捉急了,此時(shí)可以考慮使用numba 進(jìn)行加速,效果提升明顯~
(numba 安裝貌似很是繁瑣,建議安裝Anaconda,里面自帶安裝好各種常用科學(xué)計(jì)算庫(kù))
from numba import jit @jit def t(count=1000): total = 0 for i in range(int(count)): total += i return total
測(cè)試效果:
(關(guān)于__wrapped__ 見(jiàn)我的博文: 淺談解除裝飾器作用(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è)置測(cè)試一次,實(shí)際上還是取了三次的最優(yōu)值,如果取最壞值(因?yàn)樽顑?yōu)值可能是緩存下來(lái)的),則耗時(shí)為395ns * 13 大概是5us 還是比不使用的52.9us 快上大概10倍,
增大計(jì)算量可以看到使用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
如果減少計(jì)算量,可以看到當(dāng)降到明顯小值時(shí),使用加速后的效果(以最差計(jì))與不加速效果差距不大,因此如果涉及到較大計(jì)算量不妨使用jit 加速下,何況使用起來(lái)這么簡(jiǎn)便。
%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
以上這篇使用numba對(duì)Python運(yùn)算加速的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
