是否有一种简单的方法来为 Python 程序的执行计时?
澄清:整个程序
最佳答案
使用timeit
:
This module provides a simple way to time small bits of Python code. It has both command line as well as callable interfaces. It avoids a number of common traps for measuring execution times.
你需要一个字符串中的 python 语句;如果你的代码中有一个 main 函数,你可以像这样使用它:
>>> from timeit import Timer
>>> timer = Timer('main()', 'from yourmodule import main')
>>> print timer.timeit()
第二个字符串提供设置,第一个语句要计时的环境。第二部分不计时,旨在照原样设置舞台。然后第一个字符串贯穿它的步伐;默认情况下一百万次,以获得准确的时间。
如果您需要有关速度较慢的更多详细信息,请使用 python profilers
之一:
A profiler is a program that describes the run time performance of a program, providing a variety of statistics.
最简单的运行方法是在命令行中使用 cProfile
模块:
$ python -m cProfile yourprogram.py
关于python - 如何计算 Python 程序运行的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10883387/