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.
Code
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:
timeitships 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `timeit`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.