Debugging & Profiling
timeit Module
Accurately measuring small code snippets — timeit for micro-benchmarks, comparing approaches, and understanding Python performance characteristics.
Interview: Performance analysis — knowing how to benchmark code accurately is essential for optimization.
The timeit module provides accurate timing for small code snippets by running them many times and disabling garbage collection. It's designed for micro-benchmarks — comparing different ways to do the same thing. For larger-scale profiling, use cProfile instead.
Usage Modes
timeit.timeit(stmt, setup, number)— returns total time for N executionstimeit.repeat(stmt, setup, number, repeat)— runs multiple times, returns list of timestimeit.Timer(stmt, setup)— Timer object for more control- Command line:
python -m timeit "expression" - Use
min()of repeat results — best time is most representative
Best Practices
- Use
repeatand take the minimum — eliminates system noise - Put setup code in the
setupparameter — don't include it in timing - Use
numberlarge enough — aim for at least 0.1 seconds total - Compare relative performance — absolute numbers vary by system
- Be aware of caching effects — first run may be slower (JIT, file caches)
timeit vs Other Tools
- timeit: Micro-benchmarks for small expressions/functions
- cProfile: Function-level profiling of entire programs
- time.perf_counter(): Manual timing with highest-resolution clock
- line_profiler: Line-by-line timing within functions
Interview Insight
timeit disables garbage collection for accurate micro-benchmarks. Use repeat() and take the minimum to eliminate system noise. It's perfect for comparing approaches (list comprehension vs map vs loop) but not for profiling entire applications — use cProfile for that.
Use Cases
Comparing algorithms — which approach is faster for a specific task
Optimization verification — confirming that changes actually improve performance
Python idiom comparison — quantifying why certain patterns are preferred
Library comparison — measuring different libraries for the same operation
Quick performance checks — fast micro-benchmarks during development
Common Mistakes
Using time.time() instead of timeit — time.time() includes GC pauses and system noise
Not using repeat — single runs are affected by system activity
Including setup in timing — put one-time setup in the setup parameter
Too few iterations — ensure total time is at least 0.1s for meaningful results
Drawing conclusions from micro-benchmarks — they don't always reflect real-world performance