2

我正在尝试测量我的一个小的 Python 代码片段的执行时间,我想知道这样做的最佳方法是什么。

理想情况下,我想运行某种设置(这需要很长时间),然后运行一些测试代码几次,并获得这些运行的最短时间。

timeit()似乎合适,但我不确定如何在不重新执行设置的情况下获得最短时间。演示问题的小代码片段:

import timeit

setup = 'a = 2.0'  # expensive
stmt = 'b = a**2'  # also takes significantly longer than timer resolution

# this executes setup and stmt 10 times and the minimum of these 10 
# runs is returned:
timings1 = timeit.repeat(stmt = stmt, setup = setup, repeat = 10, number = 1)

# this executes setup once and stmt 10 times but the overall time of
# these 10 runs is returned (and I would like to have the minimum 
# of the 10 runs):
timings2 = timeit.repeat(stmt = stmt, setup = setup, repeat = 1, number = 10)
4

1 回答 1

1

你有没有尝试过datetime为你做你的计时?

start = datetime.datetime.now()
print datetime.datetime.now() - start #prints a datetime.timedelta object`

这将为您提供经过的时间,并且您可以以很小的开销控制它从哪里开始。

编辑:这是一个人的视频,他也用它来做一些计时,这似乎是获得运行时间的最简单方法。http://www.youtube.com/watch?v=Iw9-GckD-gQ

于 2012-06-12T14:41:57.887 回答