Python 预测循环的剩余时间

Python 预测循环的剩余时间,python,for-loop,forecasting,Python,For Loop,Forecasting,晚上好, 我试图估计到循环结束的剩余时间;我用过: 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 )

晚上好,

我试图估计到循环结束的剩余时间;我用过:

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")
但是它确实似乎工作正常,因为它最多可以运行几分钟,即使循环总共需要20秒,并且在到达终点时会迅速减少


如何才能有效、正确地预测循环的剩余时间?

您对剩余时间的计算是错误的。如果
进度
步骤需要
执行时间
。那么
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\u time\u 1
从未定义过,而是使用
datetime.datetime.now()
来实现这类功能,Python 3.3+中提供了这类功能。从文档中:

返回性能计数器的值(以小数秒为单位), i、 e.具有最高可用分辨率的时钟,用于测量短路电流 期间它确实包括睡眠期间经过的时间,并且是 全系统。返回值的参考点未定义, 因此,只有连续调用的结果之间存在差异 这是有效的

此外,您还可以使用回车代替换行符进行打印,以便在单行上打印进度报告。下面是一个源于您的代码的简短演示

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
关键字arg添加到
print
调用中,以便在发布进度报告时将其打印出来。

我认为在这一行:

remaining = execution_time * ( 1000 - progress )
您应该划分执行时间/进度,因为您想知道完成进度的1%需要多长时间

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]

76%|█████████████           | 7568/10000[00:33什么是
execution\u time\u 1
time\u by\u loop=(execution\u time\u 1.微秒/进度)
如果time\u by\u loop是一个步骤所需的时间,那么您需要
剩余=time\u by\u loop*(1000进度)
。顺便说一句,您应该使用(或者
time.process\u time()
)而不是
datetime.datetime.now()
用于此类操作。如有必要,您可以使用
time
datetime
函数将原始秒格式化为小时:分钟:秒。软件包可能会提供您所需的内容。