Python timeit Best Practices — ELI5
Say you want to know how long it takes to tie your shoes. You could glance at the clock, tie them, and glance again. But what if someone walked in front of the clock right when you looked? Or you started counting late?
Python’s timeit is like having a coach with a precise stopwatch who times you tying your shoes a hundred times, throws out the weird ones, and gives you a fair average.
When you write timeit.timeit('my_code()'), Python runs your code many times — by default, a million — and reports the total time. It also turns off the garbage collector so random cleanups don’t mess up the measurement.
Why not just use time.time()? Because a single measurement includes distractions — other programs stealing CPU time, memory cleanup happening at the wrong moment, or your laptop briefly slowing down to save battery. Running the code many times smooths all that out.
The neat part: you can use timeit right from the command line without writing a script. Just type python -m timeit "sum(range(1000))" and get an answer instantly.
People often time code once and believe the result. That’s like judging a runner by a single race on a muddy track.
The one thing to remember: timeit runs your code many times automatically so one fluke doesn’t fool you — use it instead of manual clock-checking.
See Also
- Python Algorithmic Complexity Understand Algorithmic Complexity through a practical analogy so your Python decisions become faster and clearer.
- Python Async Performance Tuning Making your async Python faster is like organizing a busy restaurant kitchen — it's all about flow.
- Python Benchmark Methodology Why timing Python code once means nothing, and how fair testing works like a science experiment.
- Python C Extension Performance How Python borrows C's speed for the hard parts — like hiring a specialist for the toughest job on the worksite.
- Python Caching Strategies Understand Python caching strategies with a shortcut-road analogy so your app gets faster without taking wrong turns.