【问题标题】:Python question about time spent关于花费时间的 Python 问题
【发布时间】:2010-06-29 21:29:09
【问题描述】:

我想知道一个特定函数在涉及递归的程序期间花费了多少时间,最好的方法是什么?

谢谢

【问题讨论】:

    标签: python timedelta


    【解决方案1】:

    最好的方法是运行一些benchmark tests(测试单个功能)或Profiling(测试整个应用程序/程序)。 Python 带有内置的分析器。

    或者,您可以返回the very basics,只需在程序开始时设置开始时间,然后在程序结束时,从开始时间中减去当前时间。这基本上是非常简单的基准测试。

    这是来自链接问题的an answer 的实现:

    import time
    start = time.time()
    do_long_code()
    print "it took", time.time() - start, "seconds."
    

    Python 的标准库中也包含something for benchmarking

    从页面上给出的示例中:

    def test():
        "Time me"
        L = []
        for i in range(100):
            L.append(i)
    
    if __name__=='__main__':
        from timeit import Timer
        t = Timer("test()", "from __main__ import test")
        print t.timeit()
    

    【讨论】:

      【解决方案2】:

      使用分析器!

      python -m cProfile -o prof yourscript.py
      runsnake prof
      

      runsnake 是查看分析输出的好工具。您当然可以使用其他工具。

      在此处了解有关 Profiler 的更多信息:http://docs.python.org/library/profile.html

      【讨论】:

      • “cPython”应该是“cProfile”。
      猜你喜欢
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多