Numba 是 Python 的即时(JIT)编译器,它最适用于使用 NumPy 数组、函数和循环的代码,用来加速for循环和numpy的纯数字的多次调用运算。
安装
conda install numba
或者
pip install numba
使用
# numba accelerate for
from numba import jit
import time
import numpy as np@jit(nopython=True) #如果未设置
nopython=True
,这是@jit
装饰器的降级模式。为获得最佳性能,请避免使用此模式
def my_function(input_array):
result = 0
for item in input_array:
result += item
return result@jit(nopython=True)
def test_function(result, item):
result += item
return resultst = time.time()
data = np.arange(100)
result = my_function(data)
print(f'cost time: {time.time()-st}')st = time.time()
data = np.arange(100)
result = my_function(data)
print(f'cost time: {time.time()-st}')st = time.time()
data = np.arange(100)
result=0
for item in data:
result = test_function(result,item)
print(f'cost time: {time.time()-st}')
(调用numba@git)结果显示
cost time: 0.03641009330749512
cost time: 1.71661376953125e-05
cost time: 0.021867036819458008
(不调用numba #@git)结果显示
cost time: 4.1961669921875e-05
cost time: 4.601478576660156e-05
cost time: 4.8160552978515625e-05
衡量numba的表现
Numba 必须在执行函数的机器代码版本之前对于你的包含特定参数的函数进行编译,这需要时间。但是,一旦编译完成,Numba 会为所特定类型的参数缓存函数的机器代码版本。如果再次使用相同类型调用它,它可以重用缓存版本而不必再次编译。
总结
上述代码如果不用numba会跑的更快。因为numba编译程序也需要时间,但是可以看到编译后的numba跑一次会快很多。因此,个人认为,numba的加速在于你需要多次调用某个for循环或某段数字计算,在经过一次编译后,后续会快非常多。
参考文献
1.1。 Numba 的约 5 分钟指南 · Numba 0.44 中文文档 · 看云