【问题标题】:Forecast the remaining time of a loop预测一个循环的剩余时间
【发布时间】:2018-05-05 11:28:57
【问题描述】:

晚上好,

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

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 秒,并且在到达终点时会迅速减少。

我怎样才能尝试有效且正确地预测剩余 时间

【问题讨论】:

  • 什么是execution_time_1
  • time_by_loop = (execution_time_1.microseconds/progress)
  • 如果time_by_loop是一个步骤所需的时间,那么你要remaining=time_by_loop * (1000-progress)
  • 顺便说一句,你应该使用time.perf_counter()(或者time.process_time())而不是datetime.datetime.now()来处理这种事情。如有必要,您可以使用timedatetime 函数将原始秒数格式化为小时:分钟:秒。
  • tqdm 包可能会满足您的需求。

标签: python for-loop forecasting


【解决方案1】:

只需使用tqdm 包:

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

它将为您打印所有内容:

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

【讨论】:

    【解决方案2】:

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

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

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

    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 调用中,以便在发布时打印进度报告。

    【讨论】:

      【解决方案3】:

      我认为在这一行:

      remaining = execution_time * ( 1000 - progress )
      

      您应该划分执行时间/进度,因为您想知道完成百分之一的进度需要多长时间。

      remaining = execution_time/progress * ( 1000 - progress )
      

      【讨论】:

        【解决方案4】:

        您对剩余时间的计算是错误的。如果 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 也从未定义

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-03
          相关资源
          最近更新 更多