1.timeit and microbenchmarks
timeit.timeit(stmt, setup, number=N) runs a snippet N times and returns the total time, averaging out noise. It is the right tool for comparing two small alternatives — never for timing a whole application, where cProfile is better.
Key features
- timeit.timeit(stmt, setup, number=1000) runs the statement 1000 times, returns total time
- The setup argument runs once, before timing starts — builds test data without counting it
- timeit disables the garbage collector during timing, for more consistent results
- python -m timeit "x in s" runs from the command line, without writing a script
- timeit is for comparing SMALL snippets — a whole real application needs cProfile instead
timeit — the interfaces worth knowing
- setup runs ONCE — s = set(range(1000)); x = 999 — before timing starts
- stmt runs number= times — x in s — timed on every single iteration
- Total time returned — summed across all runs — divide by number for per-run average
- Noise averages out — a single perf_counter() call can be skewed by one GC pause; 10,000 runs is not
Command
import timeit
t = timeit.timeit(
stmt="x in s",
setup="s = set(range(1000)); x = 999",
number=10000,
)timeit.timeit(stmt, setup, number=N) runs a snippet N times, averaging out noise — for small alternatives only.