Skip to main content
 首页 » 编程设计

python之数巴 : difference between first time execution and following executions

2024年12月31日10telwanggs

我刚开始使用 numba 来提高我的程序的性能。我已经减少了我将要呈现的情况

import numba as nb 
import numpy as np 
from time import time 
 
 
def dt_max(U,f, eps=1e-5): 
    return np.min( np.abs( U ) / ( np.abs( f ) + eps ) ) 
 
@nb.njit(cache=True) 
def fast_dt_max(U,f, eps=1e-5):       
    m=U[0] 
    if m<0 : m=-U[0] 
    for i in range(len(U)) : 
        v = abs(U[i]) / ( abs(f[i]) + eps ) 
        if v < m : m = v 
    return m 
 
 
N=100 
Niter = int(1e5) 
 
x=np.linspace(-50,50,N) 
 
t0 = time() 
for i in range(Niter): 
    dt_max(x,x) 
print('numpy',time()-t0) 
 
t0 = time() 
for i in range(Niter): 
    fast_dt_max(x,x) 
print('numba' ,time()-t0) 

我在以下分布下在 spyder 中执行整个文件:

Python 3.5.5 |Anaconda custom (64-bit)| (default, Apr  7 2018, 04:52:34) [MSC v.1900 64 bit (AMD64)] 
Type "copyright", "credits" or "license" for more information. 

问题如下。当我第一次执行这个程序时,它看起来运行良好:

runfile('E:/02-Codes/TestCode/Python_numba/bug_second_execution.py', wdir='E:/02-Codes/TestCode/Python_numba') 
numpy 0.45239996910095215 
numba 0.2964000701904297 

但是当我重复执行所有文件时:

runfile('E:/02-Codes/TestCode/Python_numba/bug_second_execution.py', wdir='E:/02-Codes/TestCode/Python_numba') 
numpy 0.45239996910095215 
numba 3.5879998207092285 
 
runfile('E:/02-Codes/TestCode/Python_numba/bug_second_execution.py', wdir='E:/02-Codes/TestCode/Python_numba') 
numpy 0.4679999351501465 
numba 3.5734000205993652 

numba 的性能完全不同。如果我在我的 spyder 环境中重新启动 Python 内核,问题再次发生:第一次执行是好的,以下所有的都不是。

所以第一个问题是:为什么?第二个是:如何避免这种情况?

谢谢你的帮助

请您参考如下方法:

非常感谢 Max 的回答。

的确,eps 的默认值是问题的原因。如果我切换到 Debug模式(感谢 Max 的提示!):

import os 
os.environ['NUMBA_DEBUG_CACHE'] = '1' 
import numba as nb 
import numpy as np 
from time import time 
 
@nb.njit(cache=True) 
def fast_dt_max(U,f, eps=1e-5): 
    m=U[0] 
    if m<0 : m=-U[0] 
    for i in range(len(U)) : 
        v = abs(U[i]) / ( abs(f[i]) + eps ) 
        if v < m : m = v 
    return m 

此代码显示在每次执行时,完成了 4 个操作(2 个加载,2 个保存)。现在,如果我通过保持 Debug模式删除 eps 的默认值:

@nb.njit(cache=True) 
def fast_dt_max(U,f, eps): 
    m=U[0] 
    if m<0 : m=-U[0] 
    for i in range(len(U)) : 
        v = abs(U[i]) / ( abs(f[i]) + eps ) 
        if v < m : m = v 
    return m 

对函数的连续调用,让每次执行只出现 2 个操作(1 加载 + 1 保存)

结论:在 numba 函数中不使用默认参数值。

谢谢!