您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“怎么加速python腳本”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“怎么加速python腳本”吧!
因?yàn)榻谝獙懬短譮or循環(huán),由于運(yùn)算量有點(diǎn)大,耗時(shí)比較久。所以就在谷歌上搜了搜有沒有辦法可以提升python for loop的速度,然后就發(fā)現(xiàn)了非常好用的模塊:Numba
Numba makes Python code fast
官方網(wǎng)址:http://numba.pydata.org/
# download from tsinghua mirror sitewget https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-5.3.1-Linux-x86_64.sh# check the help messagebash Anaconda3-5.3.1-Linux-x86_64.sh -h# then install or install into Nonexistent Custom Directory by adding -pbash Anaconda3-5.3.1-Linux-x86_64.sh# add to the environmentecho ". /home/saber/anaconda3/etc/profile.d/conda.sh" >> ~/.bashrc
from numba import jit
import time
#define function A without numba
def func_A(a1,a2):
A_result=0
for i in range(a1,a2):
A_result+=i
return A_result
#define func A1 with numba
#just add the @jit
@jit
def func_A1(a1,a2):
A1_result=0
for i in range(a1,a2):
A1_result+=i
return A1_result
#record the elasped time
def time_func(func_A_i,*args):
start = time.time()
func_A_i(*args)
end = time.time()
print("Elasped time of func %s is %.4e"%(func_A_i.__name__,end-start))
time_func(func_A,1,10000000)
time_func(func_A,1,10000000)
print()
time_func(func_A1,1,10000000)
time_func(func_A1,1,10000000)
Elasped time of func func_A is 5.4757e-01
Elasped time of func func_A is 5.3267e-01
Elasped time of func func_A1 is 5.3686e-02
Elasped time of func func_A1 is 4.7684e-06
First, recall that Numba has to compile your function for the argument types given before it executes the machine code version of your function, this takes time. However, once the compilation has taken place Numba caches the machine code version of your function for the particular types of arguments presented. If it is called again the with same types, it can reuse the cached version instead of having to compile again.
到此,相信大家對(duì)“怎么加速python腳本”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。