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.

pythonperformancetooling

See Also