Back to results for “Debugging & Profiling”
Python › Debugging & Profiling

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

Intermediate

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.

Common follow-ups: What does the 'cumtime' column specifically measure, versus 'tottime', in cProfile's output?