← All notes

Python timeit times small snippets from the command line or code, avoiding common timing traps

Answer: Use the command-line interface, python -m timeit "...", to time small bits of Python code. From code, call timeit.timeit(stmt, setup, number=10000) or timeit.repeat(...) and look at the min() of the results.

Examples

python -m timeit "'-'.join(str(n) for n in range(100))"
# 10000 loops, best of 5: 30.2 usec per loop
import timeit
timeit.timeit('"-".join(map(str, range(100)))', number=10000)
min(timeit.repeat("sorted(data)", setup="data=list(range(1000))", number=1000))
timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()

Command-line options

Things to know

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, timeit — Measure execution time of small code snippets; python/cpython (GitHub), Lib/timeit.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, timeit — Measure execution time of small code snippets; python/cpython (GitHub), Lib/timeit.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:6c5nna7x

iinventedlight. 2026. "Python timeit times small snippets from the command line or code, avoiding common timing traps." iinventedlight Library, iil:note:6c5nna7x, version of 2026-11-18. https://iinventedlight.com/library/notes/python-timeit/. License: CC-BY-4.0.

@misc{iil_note_6c5nna7x,
  author = {{iinventedlight}},
  title = {{Python timeit times small snippets from the command line or code, avoiding common timing traps}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-timeit/},
  note = {Permanent ID iil:note:6c5nna7x. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-timeit.md.