使用Numba时如何显示进度条 (tqdm不起作用) - Python

8

我一直在尝试使用 Numba 运行代码,同时我还添加了一个打印语句以查看我的代码进展:

from numba import jit,njit,prange
import numpy as np
# for minimum reproducible example
a=1e5
ar = np.random.rand(a)
at = np.random.rand(a)
an = np.random.rand(a)
###############################3


tau    = 1        # time lag
window = 6000


@njit(parallel=True)
def func_DB(ar,at,an):
    DBtotal= np.zeros((len(an)-tau))
    k = 0
    for i in prange(0,len(an)-tau,1):
        DBtotal[i] = np.sqrt((ar[i + tau]- ar[i])**2 +(at[i + tau]- at[i])**2 +(an[i + tau]- an[i])**2)
       ## To print the progress
         if i%1e5==0:
            k+=1
            print(k*1e5/len(DBtotal))
    return DBtotal


@njit(parallel=True)
def func_PVI(tau, window):
    PVI = np.zeros((len(DBtotal)))
    k = 0
    for i in prange(int(window/2),len(DBtotal)-int(window/2)): 
        PVI[i] = DBtotal[i]/np.sqrt((np.mean(DBtotal[i-int(window/2):i+int(window/2)]**2)))
       # To print the progress
        if i%1e5==0:
            k+=1
            print(k*1e5/len(DBtotal))
    return PVI 
DBtotal = func_DB(ar,at,an)
PVI     = func_PVI(DBtotal,tau, window)

然而,当代码运行时,我得到的不是我期望的结果(即随着代码进展,值从0到1递增),而是这个:
Out[:] 0.009479390005044932
      0.009479390005044932
      0.009479390005044932
      0.009479390005044932
      0.009479390005044932
      0.018958780010089864

有人能提供一种查看代码进度的方法吗?

此外,欢迎提出任何使代码更加高效的建议!


1
你会得到相同的值,因为并行进程中的函数可以获得相同的结果。你应该创建一个全局变量,并在所有进程中使用它来计算所有内容。但我不知道全局变量是否适用于进程。可能需要使用“队列”将信息发送到一个进程,该进程将计算所有内容并显示结果。 - furas
@furas 感谢您的建议,但似乎并不起作用! - user11607936
2个回答

1
我将函数分解成几个部分,并在其周围包装了一个tqdm。
而不是
@jit(nopython=True)
def dothings(A, rows, cols):
    for r in range(rows):
        for c in range(cols):
            stuff...

dothings(data, data.shape[0], data.shape[1])

我使用了

rows=data.shape[0]
@jit(nopython=True)
def dothings(A, cols, r):
#    for r in range(rows):
        for c in range(cols):
            stuff...
    
for r in tqdm.tqdm(range(rows), total=rows):
    dothings(data, data.shape[1], r)

0

试试这个:

from numba import njit,prange,objmode
@njit(parallel=True)
def harmonic_load_flow_func_time_inside():
    with objmode(time1='f8'):
        time1 = time.perf_counter()
    calc = 0
    for x in prange(1000000):
        calc += x

    with objmode():
        print('time: {}'.format(time.perf_counter() - time1),end='\r')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接