溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么加速python腳本

發布時間:2021-09-04 21:04:26 來源:億速云 閱讀:207 作者:chen 欄目:大數據

本篇內容主要講解“怎么加速python腳本”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么加速python腳本”吧!

因為近期要寫嵌套for循環,由于運算量有點大,耗時比較久。所以就在谷歌上搜了搜有沒有辦法可以提升python for loop的速度,然后就發現了非常好用的模塊:Numba
   

Numba makes Python code fast

官方網址:http://numba.pydata.org/

首先如果你沒安裝的話,可以通過pip install numba --user裝一下,或者如果你已經安裝了Anaconda3的話,那直接用conda安裝的python3就有這個模塊。

tips:用anaconda管理模塊、軟件,解決環境沖突問題,省時省力,附上linux上的安裝小教程
# 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

Numba的用法很簡單,一般是加速某個函數。如果你想加速函數x,只需要在定義函數x的時候,在def前一行加上一個裝飾器@jit就行了(就簡單的一行代碼)。

下面以筆者寫的小例子進行介紹,這個例子主要計算a1到a2所有數的加和,并用time模塊來檢測函數的運行時間:

from numba import jitimport time
#define function A without numbadef 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@jitdef func_A1(a1,a2): A1_result=0 for i in range(a1,a2):  A1_result+=i return A1_result
#record the elasped timedef 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)

其實能發現兩個函數的主體是完全一樣的,最主要的不同是在func_A1前面加了一句@jit。

運行結果如下:

Elasped time of func func_A is 5.4757e-01Elasped time of func func_A is 5.3267e-01
Elasped time of func func_A1 is 5.3686e-02Elasped time of func func_A1 is 4.7684e-06

細心的讀者可能發現了,我對每個函數都運行了2次,func_A的時間幾乎一致,func_A1第二次的時間比第一次少了四個數量級,這是因為第二次的時間才是numba加速后函數執行的時間。

通俗理解,numba第一次讀取函數時,會將函數轉換為計算更快的語言,這是編譯的過程,會消耗一些時間,之后numba將編譯存儲起來,下次遇見同類型的數據,直接讀取編譯,計算得到結果。官方解釋如下:

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.

所以總的來說numba加速后速度提升還是很大的,特別是對有想加速python腳本需求的人來說。

到此,相信大家對“怎么加速python腳本”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女