Python3:如何显示长时间运行的黑盒函数的样式时间"stopwatch"



我正在编写一个脚本,其中包含一个包含长时间运行的函数的外部库。

例如

import some_api
print("Running task X with parameters Y...")
someapi.long_task(my_data)

我在想在行尾附加一个计时器会很好,它显示当前经过的秒数,即倒计时时间而不是倒数计时器,不仅这样您就知道正在发生一些事情关于所花费时间的反馈。现在,我只是在函数完成结束时显示总运行时间。

我可以并且会使用一个我很好用的微调器,但在梳理了各种进度条库和计时库之后,我并没有更接近答案。

理想情况下,我想得到这样的东西:

Run 1 ended in 450 seconds
Run 2 running. Time far 230s

我想出了一个非常笨拙的python 3.6+解决方案(见function_progress1(。 本质上,您可以运行一个线程,该线程将在主线程运行函数时每prog_notify秒打印一次进度。 我没有添加关键字功能支持,所以你必须自己实现它。 它还打印在多行上,这不是超级优雅。不过,这里有一个开始的地方:

import time
import threading
def function_progress(func, args=None, prog_notify=10):
def wait(prog_notify, stop):
time_elapsed = 0
start = time.time()
while not stop():
if time.time() - start > prog_notify:
print(f"{func.__name__} time elapsed: {time_elapsed}")
time_elapsed += time.time() - start
start = time.time()
stop = False    
t1 = threading.Thread(target=wait, args=(prog_notify,lambda: stop))
t1.start()
if args:
res = func(*args)
else:
res = func()
stop = True
t1.join()
return res
def test0():
time.sleep(7)
print("no args")
time.sleep(5)
print("no args")
return 0
def test1(x1):
time.sleep(7)
print(x1)
time.sleep(5)
print(x1)
return x1 + x1
zero = function_progress(test0, prog_notify=2)
six = function_progress(test1,args=(3,),prog_notify=5)
print(zero, six)

测试的输出如下:

test0 time elapsed: 0
test0 time elapsed: 2.0000417232513428
test0 time elapsed: 4.000088930130005
no args
test0 time elapsed: 6.000133037567139
test0 time elapsed: 8.000176191329956
test0 time elapsed: 10.00021767616272
no args
test1 time elapsed: 0
3
test1 time elapsed: 5.00003981590271
3
0 6

使用一个global变量,您可以从具有已用时间或剩余时间的函数内部继续重写该变量。然后,您可以使用此变量绘制/显示微调器或进度条。

最新更新