Robots Atlas>ROBOTS ATLAS

Python — From Basics to Advanced · Performance and Profiling

timeit — Microbenchmarks

Performance and Profiling

Introduction

timeit is Python's built-in module for measuring the time of SMALL code snippets. It runs them thousands of times, discards outliers, and returns a robust measurement — resilient to system noise. The first reflex when asked "which version is faster?".

Three interfaces: (1) command line python -m timeit "...", (2) library API timeit.timeit(...), (3) IPython/Jupyter magics %timeit and %%timeit. All use the same engine.

Pitfalls this lesson teaches: time.time() vs time.perf_counter(), why setup is not timed, why GC matters, when repeat() beats timeit(), how autorange picks the iteration count, and how NOT to time I/O or network as if it were CPU-bound.