Numba加速Python程序
众所周知,Python和Java一样是基于虚拟机的语言,并不是像C/C++那样将程序代码编译成机器语言再运行,而是解释一行执行一行,速度比较慢。使用Numba库的JIT技术编译以后,可以明显提高程序的运行速度。
首先,使用PyCharm安装Numba库,在Project Interpreter界面可以安装。
程序代码:
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,如下图所示:
可以看到随着运算量的线性增加,sum()的运行时间几乎也是线性增加的,而sum_jit()的运行时间基本上保持不变,运算量的增加并没有带来影响。
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16