Advertisement
Intermediate Python, Debugging & Profiling

How do you use cProfile to identify which functions are consuming the most time in a larger program?

Short answer

Run your program (or a specific function call) through cProfile.run() or the command line (`python -m cProfile script.py`), which produces a detailed report showing call counts, cumulative time, and per-call time for every function invoked — pinpointing exactly where performance…

Save Python mock interview
Advertisement
AModel answer
Run your program (or a specific function call) through cProfile.run() or the command line (`python -m cProfile script.py`), which produces a detailed report showing call counts, cumulative time, and per-call time for every function invoked — pinpointing exactly where performance bottlenecks actually are, rather than guessing.
import cProfile

def slow_function():
    return sum(i * i for i in range(1_000_000))

cProfile.run("slow_function()")
# Prints a table: ncalls, tottime, percall, cumtime, percall, filename:lineno(function)
Real-world example
Identifying the actual performance bottleneck in a slow script before deciding what to optimize, rather than guessing.
Likely follow-ups
  • What does the 'cumtime' column specifically measure, versus 'tottime', in cProfile's output?
Related topics