相比较C,C++,python一直被抱怨运行速度很慢,实际上python的执行效率并不慢,而是解释器Cpython运行效率很差。
通过使用numba库的jit可以让python的运行速度提高百倍以上。
同诺简单累加,相乘的例子,可以看出。
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Victor
@Company:华中科技大学电气学院聚变与等离子研究所
@version: V1.0
@contact: 1650996069@qq.com 2018--2020
@software: PyCharm2018
@file: quickPython3.py
@time: 2018/9/21 20:54
@desc:使用numba的jit是python代码运行速度提高100倍左右
'''
'''平常运行'''
import time
def add(x,y):
tt = time.time()
s = 0
for i in range(x,y):
s += i
print('The time used: {} seconds'.format(time.time()-tt))
return s
add(1,100000000)
##########结果###############
# D:\Python3\python.exe D:/Pycharm2018Works/InsteringPython3/SomeBasics/quickPython3.py
# The time used: 6.712835788726807 seconds
# Process finished with exit code 0
'''调用numba运行'''
import time
from numba import jit
@jit
def add(x,y):
tt = time.time()
s = 0
for i in range(x,y):
s += i
print('The time used: {} seconds'.format(time.time()-tt))
return s
add(1,100000000)
##########结果###############
# D:\Python3\python.exe D:/Pycharm2018Works/InsteringPython3/SomeBasics/quickPython3.py
# The time used: 0.06396007537841797 seconds
#
# Process finished with exit code 0
Numba模块能够将处理NumPy数组的Python函数JIT编译为机器码执行,从而上百倍的提高程序的运算速度。