DEV Community

Alex Chen
Alex Chen

Posted on

Quick Tip: Benchmark Any Python Function with `timeit` the Right Way (CLI One-Liner)

Quick Tip

Don't write start = time.time() boilerplate for micro-benchmarks. The stdlib does it better, from the CLI:

python3 -m timeit -s "import re" "re.findall(r'\d+', 'abc123def456')"
# 5000000 loops, best of 5: 0.421 usec per loop
Enter fullscreen mode Exit fullscreen mode

Compare two approaches directly:

python3 -m timeit "'-'.join(['a','b','c'])"
python3 -m timeit "'a' + '-' + 'b' + '-' + 'c'"
Enter fullscreen mode Exit fullscreen mode

Why it's better than time.time():

  • Runs the snippet millions of times — one-off timings are noise (OS scheduling, CPU frequency scaling)
  • Disables garbage collection during measurement
  • best of 5 reports the minimum, which is the closest to true cost
  • -s flag sets up imports once, outside the timed loop

In a script, same API:

import timeit
t = timeit.timeit("sorted(x)", setup="import random; x=[random.random() for _ in range(1000)]", number=1000)
print(f"{t/1000*1e6:.2f} usec per call")
Enter fullscreen mode Exit fullscreen mode

If your two implementations differ by less than 2x after timeit, the "optimization" probably isn't worth the readability cost.

Powered by MonkeyCode (free AI coding assistant): https://ly.cyberserval.tech/iIETXiF

What micro-benchmark surprised you the most when you actually measured it?

Top comments (0)