Sub topic 3
Profiling a Whole Program with cProfile
This chapter assumes you can run Python scripts from a terminal, write functions and modules, and time a snippet with perf_counter or timeit. Timing a snippet tells you how long one piece takes. It does not tell you which piece of a larger program to look at. A profiler answers that question.
What cProfile does
cProfile is a deterministic profiler in the standard library. It hooks into the interpreter and records every function call: how many times it ran, and how much time it took. Because it records every call, it adds overhead. Absolute times in a profile are inflated, but the relative ranking of functions is usually reliable.
Profiling from the command line
The quickest way to profile a script is to run it under the cProfile module. The -s option picks the sort column.
python -m cProfile -s cumulative myscript.pySorting by cumulative puts the call chains that contain the most time at the top. This is a good first view, because it shows which high-level function to investigate.
Profiling part of a program
Often you only care about one section, and you do not want startup code in the report. A cProfile.Profile object works as a context manager and records only the code inside the block. The pstats module then sorts and prints the results.
import cProfile
import pstats
def slow_sum(n):
total = 0
for i in range(n):
total += i * i
return total
def main():
for _ in range(50):
slow_sum(100_000)
with cProfile.Profile() as profiler:
main()
stats = pstats.Stats(profiler)
stats.sort_stats("cumulative").print_stats(5)print_stats(5) limits the output to the five most expensive entries. Without a limit, a real program prints hundreds of lines.
The columns in the report
The report has one row per function. These are the columns you will use most.
| Column | Meaning |
|---|---|
| `ncalls` | Number of calls to the function |
| `tottime` | Time spent in the function itself, excluding functions it called |
| `cumtime` | Time spent in the function and everything it called |
| `percall` | The time divided by the number of calls (it appears twice, once for each time column) |
In the example above, main has a large cumtime but a tiny tottime, because it only loops and calls slow_sum. slow_sum has nearly all of the tottime. The next chapter covers how to read these differences in detail.
Saving a profile for later
For a long run, save the raw data to a file and analyze it afterwards. You can then try different sort orders without running the program again.
python -m cProfile -o profile.out myscript.py
python -m pstats profile.outThe second command opens an interactive prompt. Inside it, sort tottime and stats 10 re-sort the data and print the top ten rows.
Common mistakes
- Profiling with too little work. If the run takes a few milliseconds, the report is dominated by import and startup costs. Use a realistic input size.
- Trusting absolute times. The profiler's overhead slows down code with many small calls more than code with a few large ones. Confirm any fix with
timeitorperf_counter, which have less overhead. - Reading only the top row. The most expensive line by
cumulativeis often justmainor a framework entry point. Look further down for the function whose owntottimeis high. - Ignoring call counts. A function that is fast per call but runs a million times can still be the hot spot.
Exercise
You profile a script with python -m cProfile -s cumulative myscript.py. The top row is main, with a large cumtime and a tottime near zero. What does this tell you, and what should you look at next?
Show answer
It tells you that main spends almost no time in its own code. Nearly all of its time goes to functions it calls. That makes main a pointer, not the hot spot. Look further down the report, or re-sort by tottime, to find the function with a high own time or a very high call count. Fix that function, then measure again.