Python question about time spent

徘徊边缘 提交于 2019-12-10 09:38:40

问题


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


回答1:


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.

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.

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



回答2:


Use the profiler!

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

runsnake is a nice tool for looking at the profiling output. You can of course use other tools.

More on the Profiler here: http://docs.python.org/library/profile.html



来源:https://stackoverflow.com/questions/3144898/python-question-about-time-spent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!