from numba import jit
import numpy as np
x = np.arange(100).reshape(10, 10)
@jit(nopython=True) # Set "nopython" mode for best performance
def go_fast(a): # Function is compiled to machine code when called the first time
trace = 0
for i in range(a.shape[0]): # Numba likes loops
trace += np.tanh(a[i, i]) # Numba likes NumPy functions
return a + trace # Numba likes NumPy broadcasting
print(go_fast(x))
from numba import jit
import pandas as pd
x = {'a': [1, 2, 3], 'b': [20, 30, 40]}
@jit
def use_pandas(a): # Function will not benefit from Numba jit
df = pd.DataFrame.from_dict(a) # Numba doesn't know about pd.DataFrame
df += 1 # Numba doesn't understand what this is
return df.cov() # or this!
print(use_pandas(x))
1.1.3。什么是nopython
模式?
Numba @jit
装饰器从根本上以两种编译模式运行, nopython
模式和object
模式。在go_fast
上面的例子中, nopython=True
在@jit
装饰器中设置,这是指示Numba在nopython
模式下操作。nopython
编译模式的行为本质上是编译装饰函数,以便它完全运行而不需要Python解释器的参与。这是使用Numba jit
装饰器的推荐和最佳实践方式,因为它可以带来最佳性能。
如果编译nopython
模式失败,Numba可以编译使用 ,如果没有设置,这是装饰器的 后退模式(如上例所示)。在这种模式下,Numba将识别它可以编译的循环并将它们编译成在机器代码中运行的函数,并且它将运行解释器中的其余代码。为获得最佳性能,请避免使用此模式objectmode
@jit
nopython=True
use_pandas