Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceMiddleCommonPerformance

How do you find which function is actually slow in a Python program before optimizing it?

Answer

The standard first step is `cProfile`, the built-in deterministic profiler: running `python -m cProfile -s cumulative script.py` (or wrapping code with `cProfile.run()`) instruments every function call and reports call counts, total time, and cumulative time per function, which usually reveals the real bottleneck instead of the one a developer assumed. Guessing at performance without measuring first is a well-known trap, since the actual hot path is frequently in a different place than intuition suggests, especially once caching, I/O, or an unexpectedly-called helper function are involved.

Strong answer includes

  • cProfile is the built-in deterministic profiler for this
  • reports call counts, total time and cumulative time per function
  • measure before optimizing, intuition about hot paths is often wrong

Practical example

Python example
python -m cProfile -s cumulative slow_report.py

might reveal that 90% of the runtime is spent in a single

Python example
format_currency()

helper called deep inside a loop, not in the database query everyone assumed was the bottleneck.

#profiling#performance

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules