numba用户手册
2.@jit
1.1.@jit
import math
import numpy as np
import numba as nb
from numba.typed import List,Dict
from numba import jit,njit,int32,float32,float64
--------------------------------------------------------------------------------------------------------------
# 实例1.1:推断类型
@jit #支持所有类型(每次检查参数类型计算速度降低)编译将推迟到函数执行之前.
def f(x, y):return x + y
f(1j, 2) #根据输入类型来单独编译
--------------------------------------------------------------------------------------------------------------
# 实例1.2:给出函数类型
@jit("f8[:](f4,i4,i4)")
@jit(["int32(int32, int32)", "float32(float32, float32)"])
@jit(float64[:](float32,int32,nb.int_)) #返回1D数组
@jit("f8[:](f4,i4,i4)", nopython=True, nogil=True)
@jit("float64[:](float32,int32,int_)", nopython=True, nogil=True)
def fun_f(a, b, n):
res = np.empty(n, dtype=np.float64)
for i in range(n):
res[i] = i*a+b
return res
fun_f(11,22,2)
--------------------------------------------------------------------------------------------------------------
#实例1.3:list参数
@njit
def add_lst(lst,x):
for i,v in enumerate(lst):lst[i]+=x
return lst
nb_lst = nb.typed.List()
[ nb_lst.append(x) for x in [1,2,3]]
add_lst(nb_lst,100) #ListType[int64]([101, 102, 103])
--------------------------------------------------------------------------------------------------------------
#实例1.4:Numba编译函数可调用其他编译函数
@jit #其他函数必须被@jit装饰,否则Numba可产生慢得多的代码
def square(x):return x ** 2
@jit
def hypot(x, y):return math.sqrt(square(x) + square(y))
--------------------------------------------------------------------------------------------------------------
2.参数nogil #将代码优化为仅适用于本机类型和变量,释放全局解释器锁(GIL)
@jit(nogil=True) #警惕多线程编程的常见陷阱(一致性,同步,竞争条件等)
def f(x, y):
return x + y
--------------------------------------------------------------------------------------------------------------
3.参数cache #将函数编译结果写文件缓存,避免每次调用程序都编译
@jit(cache=True)
def f(x, y):
return x + y
--------------------------------------------------------------------------------------------------------------
4.参数parallel=True+nopython=True #为具有并行语义函数中操作启用自动并行化
@jit(nopython=True, parallel=True)
def f(x, y):
return x + y
--------------------------------------------------------------------------------------------------------------