On this page
  1. timeit
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Comparing Two Implementations with Timer.repeat()
  7. 2. Quick Command-Line Benchmarking
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

timeit

Prev: time | Up: stdlib_module | Next: tkinter
Rel: typing, annotationlib, pydoc, pydoc_data, doctest
Ref: docs.python.org — timeit
Tags: #public #python3 #stdlib


Import

import timeit

Overview

Micro-benchmarking harness for comparing the execution speed of small Python expressions and functions (timeit, repeat, Timer, and python -m timeit). Disables garbage collection during measurement by default and runs enough iterations to smooth out OS jitter.

Quick Start

import timeit

elapsed = timeit.timeit("'-'.join(str(n) for n in range(100))", number=1000)
assert elapsed > 0.0

Implementation Walkthrough

1. Comparing Two Implementations with Timer.repeat()

Always report the minimum across repeats (the fastest clean run with the least OS background interference), not the mean:

import timeit

data = list(range(1000))
t_comp = min(timeit.repeat(lambda: [x * 2 for x in data], repeat=5, number=500))
t_map = min(timeit.repeat(lambda: list(map(lambda x: x * 2, data)), repeat=5, number=500))
assert t_comp > 0 and t_map > 0

2. Quick Command-Line Benchmarking

python3 -m timeit -s "data = list(range(1000))" "sum(data)"

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes