在命令行中,我可以执行以下操作:
python -m timeit 'a = 1'
根据文档:
If -n is not given, a suitable number of loops is calculated by trying successive powers of 10 until the total time is at least 0.2 seconds.
这很好用,但是在我的程序中使用 timeit
时如何才能获得相同的行为?如果我在 timeit.timeit
调用中省略 number
参数,它将默认为 1000000
。
最佳答案
文档并没有明确表明存在这样的功能,我假设不存在。幸运的是,定义一个为您完成此任务的包装器并不太难:
import timeit
def auto_timeit(stmt='pass', setup='pass'):
n = 1
t = timeit.timeit(stmt, setup, number=n)
while t < 0.2:
n *= 10
t = timeit.timeit(stmt, setup, number=n)
return t / n # normalise to time-per-run
关于python - 强制 timeit 自动选择语句执行的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302103/