timeit Compares Snippets With Repeated Runs

timeit repeats a statement many times and repeat() returns one result per round, so the minimum — least disturbed by background load — is the honest number.

PythonCli Tooling

Code

pythonsnippet
21 lines
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))

Inside the snippet

The demo data lives in module-level bindings: setup, t_sum, t_loop, best.

What to watch for

  • Runs on the standard library alone: timeit ships with Python, so there is no package to install and no version to pin.

Putting it to use

The demo output is labeled (sum():, for loop:, best of 3 rounds:), so the operation behind every printed line is easy to name.

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `timeit`, which the package manager must provide.