【发布时间】:2022-01-24 02:01:06
【问题描述】:
我正在测试一些采用 numpy 数组的函数的 numba 性能,并进行比较:
import numpy as np
from numba import jit, vectorize, float64
import time
from numba.core.errors import NumbaWarning
import warnings
warnings.simplefilter('ignore', category=NumbaWarning)
@jit(nopython=True, boundscheck=False) # Set "nopython" mode for best performance, equivalent to @njit
def go_fast(a): # Function is compiled to machine code when called the first time
trace = 0.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
class Main(object):
def __init__(self) -> None:
super().__init__()
self.mat = np.arange(100000000, dtype=np.float64).reshape(10000, 10000)
def my_run(self):
st = time.time()
trace = 0.0
for i in range(self.mat.shape[0]):
trace += np.tanh(self.mat[i, i])
res = self.mat + trace
print('Python Diration: ', time.time() - st)
return res
def jit_run(self):
st = time.time()
res = go_fast(self.mat)
print('Jit Diration: ', time.time() - st)
return res
obj = Main()
x1 = obj.my_run()
x2 = obj.jit_run()
输出是:
Python Diration: 0.2164750099182129
Jit Diration: 0.5367801189422607
如何获得此示例的增强版本?
【问题讨论】:
-
排除 Numba 的编译时间(即忽略 JIT 函数的首次运行)时,我无法在我的机器上重现问题:两者都需要大约 0.1 秒。
-
这就是答案。在我的机器上测试,我得到
Python duration: 0.23然后Jit duration: 0.79 0.20 0.20 0.20 0.20 ...。 -
你只计时第一次运行吗?
-
是的,我正在计时第一次运行。有什么方法可以在不运行的情况下初始化 jit 函数?因为我将在正常工作中运行一次该功能