准确测量Python函数执行时间
7 个回答
8
timeit模块看起来是用来测试算法性能的,而不是简单地监控一个应用程序。你最好的选择可能是使用time模块,在你感兴趣的代码段开始和结束时分别调用time.time()
,然后把这两个数字相减。要注意,你得到的数字可能会有很多小数位,这些小数位可能超过了系统计时器的实际精度。
30
你可以创建一个计时上下文(可以参考PEP 343),这样就能很简单地测量一段代码的执行时间。
from __future__ import with_statement
import time
class Timer(object):
def __enter__(self):
self.__start = time.time()
def __exit__(self, type, value, traceback):
# Error handling here
self.__finish = time.time()
def duration_in_seconds(self):
return self.__finish - self.__start
timer = Timer()
with timer:
# Whatever you want to measure goes here
time.sleep(2)
print timer.duration_in_seconds()
39
根据Python的文档,这与不同操作系统中时间函数的准确性有关:
默认的计时器函数是依赖于平台的。在Windows上,time.clock()的精度是微秒,而time.time()的精度是1/60秒;在Unix系统上,time.clock()的精度是1/100秒,而time.time()则更精确。在这两种平台上,默认的计时器函数测量的是实际的墙钟时间,而不是CPU时间。这意味着在同一台计算机上运行的其他进程可能会影响计时……在Unix上,你可以使用time.clock()来测量CPU时间。
直接从timeit.py
的代码中提取:
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time
此外,它还直接为你设置运行时代码。如果你使用time
,你就得自己来做。这当然节省了你的时间。
Timeit的设置:
def inner(_it, _timer):
#Your setup code
%(setup)s
_t0 = _timer()
for _i in _it:
#The code you want to time
%(stmt)s
_t1 = _timer()
return _t1 - _t0
Python 3:
从Python 3.3开始,你可以使用time.perf_counter()
(系统范围的计时)或time.process_time()
(进程范围的计时),就像以前使用time.clock()
一样:
from time import process_time
t = process_time()
#do some stuff
elapsed_time = process_time() - t
新的函数process_time
不会包括睡眠期间的时间。
Python 3.7+:
从Python 3.7开始,你还可以使用process_time_ns()
,这个函数和process_time()
类似,但返回的时间单位是纳秒。