用途timeit:
该模块提供了一种简单的方法来计算一小段Python代码.它既有命令行,也有可调用的接口.它避免了许多用于测量执行时间的常见陷阱.
你需要一个字符串中的python语句; 如果你的代码中有一个main函数,你可以像这样使用它:
>>> from timeit import Timer
>>> timer = Timer('main()', 'from yourmodule import main')
>>> print timer.timeit()
Run Code Online (Sandbox Code Playgroud)
第二个字符串提供设置,第一个语句的定时环境.第二个部分没有定时,用于设置阶段.然后第一个字符串贯穿它的步伐; 默认为百万次,以获得准确的时间.
如果您需要更详细的信息,请使用以下方法之一python profilers:
分析器是一个描述程序运行时性能的程序,提供各种统计信息.
运行此操作的最简单方法是使用cProfile命令行中的模块:
$ python -m cProfile yourprogram.py
Run Code Online (Sandbox Code Playgroud)
您可能想要使用内置的分析器.
您还可以使用以下简单的装饰器来测量函数的运行时间:
import time
def myprof(func):
def wrapping_fun(*args):
start = time.clock()
result = func(*args)
end = time.clock()
print 'Run time of %s is %4.2fs' % (func.__name__, (end - start))
return result
return wrapping_fun
Run Code Online (Sandbox Code Playgroud)
用法:
@myprof
def myfun():
# function body
Run Code Online (Sandbox Code Playgroud)