预测一个循环的剩余时间

Forecast the remaining time of a loop

晚上好,

我正在尝试估计剩余时间到循环结束;我用过:

start = datetime.now()
progress = 0

for i in range(1000): 

    #do a few calculations

    progress += 1

    stop = datetime.now()
    execution_time = stop-start 

    remaining = execution_time * ( 1000 - progress )

    print("Progress:", progress, "%, estimated", remaining, "time remaining")

但它 not 似乎工作正常,因为它最多可达几分钟,即使循环总共需要 20 秒,并且在到达终点时迅速减少。

我如何尝试有效且正确地预测循环的剩余时间

您计算的剩余时间有误。如果需要 execution_time progress 步。那么 1000 步需要多少?

简单的交叉乘法给出了总时间。从已经过去的时间中减去它,就是剩余时间。

remaining_time = execution_time * 1000 / progress - execution_time
percent_complete =  (progress  / 1000) * 100     #You can simplify this if you like
print("Progress:", percent_complete , "%, Estimated", remaining_time, "time remaining")

而且你的变量 execution_time_1 从未被定义

您可以使用 Python 3.3+ 中提供的 time.perf_counter(),而不是使用 datetime.datetime.now()。来自文档:

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

此外,您可以使用回车符 return 代替换行符进行打印,以便将进度报告打印在一行中。这是从您的代码派生的简短演示。

from time import sleep, perf_counter

fmt = "  Progress: {:>3}% estimated {:>3}s remaining"
num = 1000

start = perf_counter()
for i in range(1, num + 1):
    # Simulate doing a few calculations
    sleep(0.01)

    stop = perf_counter()
    remaining = round((stop - start) * (num / i - 1))
    print(fmt.format(100 * i // num, remaining), end='\r')
print()

根据您的终端(和 Python 版本),您可能还需要将 flush=True 关键字参数添加到 print 调用中,以便将进度报告打印为它们已发行。

我认为在这一行中:

remaining = execution_time * ( 1000 - progress )

你应该除execution_time/progress,因为你想知道完成百分之一的进度需要多长时间。

remaining = execution_time/progress * ( 1000 - progress )

只需使用tqdm包:

from tqdm import tqdm
for i in tqdm(range(10000)):
    dosomthing()

它将为您打印所有内容:

76%|█████████████           | 7568/10000 [00:33<00:10, 229.00it/s]