python - 强制 timeit 自动选择语句执行的次数

标签 python python-3.x timeit

在命令行中,我可以执行以下操作:

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/

相关文章:

python - 无法强制脚本重试五次,除非中间出现 200 状态

python - timeit.timeit 方法的装饰器?

python - 在 timeit() 中从同一模块调用方法时导入错误

Python Selenium 错误处理

python - GAE+ Picasa 大量使用。限制或引用

python - matplotlib 不支持生成器作为输入

python - 使用 Python 请求测量网站加载时间

python - 如何在 Pandas 中创建叠加条形图

python - 使用线程时不触发 Pyttsx3 回调

python-3.x - PyTest - 将模拟应用于所有测试