【发布时间】:2018-12-25 07:40:09
【问题描述】:
将纯 Python 无操作函数与以@numba.jit 修饰的无操作函数进行比较,即:
import numba
@numba.njit
def boring_numba():
pass
def call_numba(x):
for t in range(x):
boring_numba()
def boring_normal():
pass
def call_normal(x):
for t in range(x):
boring_normal()
如果我们用%timeit 计时,我们会得到以下结果:
%timeit call_numba(int(1e7))
792 ms ± 5.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit call_normal(int(1e7))
737 ms ± 2.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
一切都完全合理; numba 函数的开销很小,但并不多。
如果我们使用cProfile 来分析这段代码,我们会得到以下结果:
cProfile.run('call_numba(int(1e7)); call_normal(int(1e7))', sort='cumulative')
ncalls tottime percall cumtime percall filename:lineno(function)
76/1 0.003 0.000 8.670 8.670 {built-in method builtins.exec}
1 6.613 6.613 7.127 7.127 experiments.py:10(call_numba)
1 1.111 1.111 1.543 1.543 experiments.py:17(call_normal)
10000000 0.432 0.000 0.432 0.000 experiments.py:14(boring_normal)
10000000 0.428 0.000 0.428 0.000 experiments.py:6(boring_numba)
1 0.000 0.000 0.086 0.086 dispatcher.py:72(compile)
cProfile 认为调用 numba 函数的开销很大。
这延伸到“真实”代码:我有一个简单地调用我的昂贵计算的函数(计算是 numba-JIT 编译的),cProfile 报告说包装函数占用了总时间的三分之一左右。
我不介意 cProfile 增加一点开销,但如果它在哪里增加开销的地方非常不一致,那它就不是很有帮助。有谁知道为什么会发生这种情况,是否有什么可以做的,和/或是否有任何替代分析工具不会与 numba 发生不良交互?
【问题讨论】:
标签: python performance profiling numba cprofile