【问题标题】:How to find how long the execution time will take before starting?如何找到开始之前的执行时间?
【发布时间】:2019-01-12 07:31:38
【问题描述】:

我们可以测量脚本执行所需的时间。如这个问题:How do I get time of a Python program's execution?

但我想要的是在执行之前找到执行代码所需的时间。

示例 1:

执行脚本时,首先要打印的是这样的:

this function will take 1 min 40 seconds to be executed

示例 2:

到目前为止执行的百分比。例如,一分钟后,百分比为:60%,并不断增加,直到达到100%

【问题讨论】:

    标签: python python-3.x python-2.7 time


    【解决方案1】:

    这个问题的一个完全通用的解决方案是解决the halting problem,这在数学上已被证明是不可能的。

    对于更特殊的情况,可以这样做。对于某些算法,如果您知道必须完成多少工作并且可以定期检查已完成的工作量,那么您可以更新百分比。您还可以根据百分比的进展速度估算剩余时间,但这通常可能不准确。

    【讨论】:

    • 非常感谢。我认为这就是安装软件包时在 Linux 中的完成方式,然后它会为每个 5% 添加 = 直到完成整行,如下所示:|==============|
    【解决方案2】:

    请注意,当您执行一个函数时,时间取决于您的算法以及您的机器速度。为了在不执行代码的情况下计算时间,您可能必须提供一些初始参数,或者使用机器学习代码通过代码计算执行时间,但这似乎非常困难。

    顺便说一句,使用 import timeit 试试这个。

    只需节省代码执行前后的时间并减去它们!但是这种方法并不精确,因为可能会暂时运行一个后台进程,这会中断代码执行,并且您会在小代码 sn-ps 的运行时间上得到显着变化。

    timeit 运行您对代码的 sn-p 数百万次(默认值为 1000000),以便您获得在统计上最相关的代码执行时间测量!

    # 导入需要的模块 导入时间

    # code snippet to be executed only once
    mysetup = "from math import sqrt"
    
    # code snippet whose execution time is to be measured
    mycode = '''
    def example():
        mylist = []
        for x in range(100):
            mylist.append(sqrt(x))
    '''
    
    # timeit statement
    print timeit.timeit(setup = mysetup,
                        stmt = mycode,
                        number = 10000)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2020-04-28
      • 2021-08-09
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      相关资源
      最近更新 更多