2
我想测量我的一个小型Python代码片段的执行时间,我想知道这样做的最佳方式是什么。避免在timeit.repeat()基准测试中设置昂贵的设置
理想情况下,我想运行某种设置(需要很长时间),然后运行一些测试代码几次,并获得这些运行的最短时间。
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)
您可以将安装程序的结果存储在变量中吗? –
由于涉及更复杂的数据类型(scipy.sparse.linalg.LinearOperator),我们无法将结果存储在字符串中。 – andrenarchy