衆所周知,Python和Java同樣是基於虛擬機的語言,並非像C/C++那樣將程序代碼編譯成機器語言再運行,而是解釋一行執行一行,速度比較慢。使用Numba庫的JIT技術編譯之後,能夠明顯提升程序的運行速度。dom
首先,使用PyCharm安裝Numba庫,在Project Interpreter界面能夠安裝。函數
程序代碼:spa
import numpy as np from numba import jit import time @jit def sum_jit(arr): s_time = time.time() m = arr.shape[0] result = 0.0 for i in range(m): result += arr[i] e_time = time.time() return (e_time-s_time) def sum(arr): s_time = time.time() m = arr.shape[0] result = 0.0 for i in range(m): result += arr[i] e_time = time.time() return (e_time-s_time) def main(): n = int(10.0*1e6) array = np.random.random(n) t1 = sum_jit(array) t2 = sum(array) print("Time with JIT:", t1) print("Time without JIT:", t2) if __name__ == '__main__': main()
上面代碼的sum()和sum_jit()兩個函數徹底相同,區別在於sum_jit()添加了@jit註解,表面該函數使用Numba JIT進行編譯之後再運行,而sum()是不編譯的運行。對main()中n的值取1×106~10×106,計算每一個值兩個函數運行的時間,單位爲Second,以下圖所示:code
能夠看到隨着運算量的線性增長,sum()的運行時間幾乎也是線性增長的,而sum_jit()的運行時間基本上保持不變,運算量的增長並無帶來影響。blog