我正在编写一个脚本,其中包含一个外部库,其中包含一个长时间运行的函数。
例如
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+ 想出了一个相当 hacky 的解决方案(参见 function_progress1
)。本质上,您可以运行一个线程,当主线程运行该函数时,该线程将每隔 prog_notify
秒打印出进度。我没有添加关键字函数支持,因此您必须自己实现它。它还打印不止一行,这不是 super 优雅。不过,这是一个开始的地方:
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
关于Python3 : How to show "stopwatch" style time of long running blackbox function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263564/