从命令行运行时,
python -mtimeit -s'from script import f, x' 'f(x)'
该timeit
脚本找到调用该函数至少 0.2 秒所需的迭代次数。Endolith 已将该代码合并为一个函数:
def timeit_auto(stmt="pass", setup="pass", repeat=3, duration=0.2):
"""
https://stackoverflow.com/q/19062202/190597 (endolith)
Imitate default behavior when timeit is run as a script.
Runs enough loops so that total execution time is greater than 0.2 sec,
and then repeats that 3 times and keeps the lowest value.
Returns the number of loops and the time for each loop in microseconds
"""
t = timeit.Timer(stmt, setup)
# determine number so that 0.2 <= total time < 2.0
for i in range(1, 10):
number = 10 ** i
x = t.timeit(number) # seconds
if x >= duration:
break
r = t.repeat(repeat, number)
best = min(r)
usec = best * 1e6 / number
return number, usec
标准库中的timeit 代码可以在这里找到。