简体   繁体   English

关于花费时间的Python问题

[英]Python question about time spent

I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it? 我想知道特定函数在程序持续期间花了多少时间涉及递归,最好的方法是什么?

Thank you 谢谢

The best way would be to run some benchmark tests (to test individual functions) or Profiling (to test an entire application/program). 最好的方法是运行一些基准测试 (测试单个函数)或分析 (测试整个应用程序/程序)。 Python comes with built-in Profilers. Python附带内置的Profilers。

Alternatively, you could go back to the very basics by simply setting a start time at the beginning of the program, and, at the end of the program, subtracting the current time from the start time. 或者,你可以回去了很基础 ,只需在程序开始时设置的开始时间,并在节目的最后,从起始时间减去当前时间。 This is basically very simple Benchmarking. 这基本上是非常简单的基准测试。

Here is an implementation from the an answer from the linked question: 以下是来自链接问题的答案的实现:

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

Python has something for benchmarking included in its standard library, as well. Python也有标准库中包含的基准测试功能

From the example give on the page: 从示例中给出页面:

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()

Use the profiler! 使用探查器!

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

runsnake is a nice tool for looking at the profiling output. runsnake是查看分析输出的一个很好的工具。 You can of course use other tools. 你当然可以使用其他工具。

More on the Profiler here: http://docs.python.org/library/profile.html 有关Profiler的更多信息,请访问: http//docs.python.org/library/profile.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM