Skip to main content
 首页 » 编程设计

python之如何编译 numba python 代码并存储它

2025年05月04日8mate10pro

我一直在使用 numba 来加速一些 for 循环,获得了很好的结果。我如何预编译代码而不是及时编译代码(这需要一些时间)?

这是一个例子:

import numba as nb 
import numpy as np 
import time.time() 
 
Nk = 5 
Nl = 6 
Nx = 7 
Ny = 8 
A = np.random.rand(Nk, Nl, Nx, Ny) 
 
@nb.jit(nopython=True) 
def Loop( A, X, Y ): 
    Nk = A.shape[0] 
    Nl = A.shape[1] 
    Nx = A.shape[2] 
    Ny = A.shape[3] 
    for ik in range(Nk): 
        for il in range(Nl): 
            for ix in range(Nx): 
                for iy in range(Ny): 
                    Y[ik, il] += A[ik, il, ix, iy]*X[ix,iy] 
    return Y 
 
Y = np.zeros([Nk, Nl]) 
X = np.random.rand(Nx, Ny) 
Y = Loop( A, X , Y ) 

我想要的是以某种方式保存已编译的函数,这样我就不需要每次都编译它。

请您参考如下方法:

原则上你有 pycc,但截至今天 (numba 0.17) the API is not stable :

The API for ahead of time compilation isn’t stabilized. Adventurous users can still try the pycc utility which is installed as part of Numba.

但是熟练的读者可以提取一些信息from the source itself .