← 中文资源

简体中文版本

timeit 用重复运行对比片段开销

timeit 把语句重复执行上万次以压低单次噪声,repeat 返回每轮结果——取最小值最接近真实成本,因为它受后台负载干扰最小。

阅读英文原文

实现说明

演示用的数据放在这几个模块级绑定中:setup、t_sum、t_loop、best。

使用要点

  • 依赖外部包 timeit,运行前需要先安装。
  • 跑完文件,输出里会留下标记——sum():、for loop:、best of 3 rounds:。

常见问题

要先安装哪些包?

需要。导入解析到 timeit,由包管理器提供。

代码示例

import timeit

setup = "values = list(range(1_000))"

# timeit repeats the statement many times so one noisy run cannot dominate
t_sum = timeit.timeit("sum(values)", setup=setup, number=10_000)
t_loop = timeit.timeit(
    "total = 0\nfor v in values:\n    total += v",
    setup=setup,
    number=10_000,
)
print(f"sum():    {t_sum:.3f}s")
print(f"for loop: {t_loop:.3f}s")

# repeat returns one result per round; the minimum is the number to report,
# because the fastest round is the one least disturbed by background load
best = min(timeit.repeat("sum(values)", setup=setup, number=10_000, repeat=3))
print(f"best of 3 rounds: {best:.3f}s")

# Tiny expressions need no setup string at all
print("1 + 1 x 1e6:", timeit.timeit("1 + 1", number=1_000_000))