如何在Python中计算程序运行时间?
在Python中,如何计算程序运行时间呢?
5 个回答
69
我不知道这是不是更快的替代方案,但我有另一个解决办法 -
from datetime import datetime
start=datetime.now()
#Statements
print datetime.now()-start
350
快速的替代方案
import timeit
start = timeit.default_timer()
#Your statements here
stop = timeit.default_timer()
print('Time: ', stop - start)
63
你可以看看 timeit
模块:
http://docs.python.org/library/timeit.html
或者 profile
模块:
http://docs.python.org/library/profile.html
这里还有一些不错的教程:
http://www.doughellmann.com/PyMOTW/profile/index.html
http://www.doughellmann.com/PyMOTW/timeit/index.html
还有 time
模块也可能会对你有帮助,不过我更推荐前面提到的两个模块来测试和分析代码的性能: