Sub topic 3
Profiling a whole program with cProfile
This chapter assumes you can write and run Python scripts from a terminal and that you have already timed small snippets with time.perf_counter or timeit. Timing tells you that something is slow. A profiler tells you where the time goes. Here you will run cProfile on a whole program, save its results, and filter them with pstats. The next chapter covers interpreting the numbers in detail.
What cProfile is
cProfile is a profiler in the standard library. It is a deterministic profiler: it hooks every function call and return, and records how many calls happened and how much time each function used. It does not guess or sample. Every call is counted.
The hooks have a cost. A program under cProfile usually runs slower than normal, and the slowdown is not evenly spread. Functions that are called millions of times with very little work inside them are slowed down the most. Treat the numbers as a way to rank functions, not as exact production timings.
Profiling from the command line
The quickest way to profile is to run your script through the cProfile module:
python -m cProfile -s cumulative myscript.pyPython runs myscript.py as usual. When the script finishes, it prints a table of every function that was called. The -s cumulative option sorts that table by cumulative time, so the most expensive call chains come first.
Some details that matter in practice:
- Arguments after the script name go to your script, as normal:
python -m cProfile -s tottime myscript.py --input data.csv. - To profile a module, use
-m:python -m cProfile -m mypackage.cli. - The script's own output is mixed with the report. Redirect the report to a file, or save the data with
-o(shown below), if that is a problem. - The script runs with
__name__ == "__main__", so code under that guard runs normally.
Profiling a block of code
Sometimes you want to profile one part of a program. Setup and teardown would otherwise add noise to the report. Use a cProfile.Profile object as a context manager. Only the code inside the with block is recorded. The context-manager form needs Python 3.8 or later.
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)pstats.Stats wraps the recorded data. sort_stats chooses the ordering, and print_stats(5) prints only the first five rows. Both methods return the Stats object, so you can chain them as shown.
If you prefer explicit calls, profiler.enable() and profiler.disable() do the same thing. Put disable() in a finally block so an exception cannot leave the profiler running.
There are two other forms:
cProfile.run("main()")profiles a string of code and prints a report. It is handy in a REPL.profiler.runcall(func, *args)profiles one call and returns its result.
Reading the report columns
The report has one row per function. These are the columns:
| Column | Meaning |
|---|---|
| `ncalls` | Number of calls. Recursive functions show two numbers, such as `177/1`: total calls and primitive (non-recursive) calls. |
| `tottime` | Total time spent in the function itself, excluding time in the functions it called. |
| `percall` (first) | `tottime` divided by `ncalls`. |
| `cumtime` | Cumulative time: time in the function plus everything it called. |
| `percall` (second) | `cumtime` divided by primitive calls. |
| `filename:lineno(function)` | Where the function is defined. |
Two columns are called percall. The first is derived from tottime and the second from cumtime. This is a common source of confusion.
A function with a large cumtime and a small tottime is mostly a pass-through, such as main. Its time is spent in functions it calls. A function with a large tottime does the work itself, and it is usually the better place to look first. The next chapter goes into this distinction.
Built-in functions appear in the report too. Calling sum or list.append shows up as {built-in method builtins.sum} or {method 'append' of 'list' objects}. These have no source file.
Saving a profile and analyzing it later
Printing a long report to the terminal makes it hard to explore. Save the raw data to a file instead:
python -m cProfile -o myscript.prof myscript.pyThe .prof file is a binary file that pstats can read. You can load it as many times as you like and try different sort orders without running the program again. Here is a small script that does this:
import pstats
stats = pstats.Stats("myscript.prof")
stats.strip_dirs()
stats.sort_stats("tottime")
stats.print_stats(10)strip_dirs() removes directory prefixes from file names, which makes rows shorter. It also merges rows that end up with the same name after stripping, so use it for reading, not for careful analysis of similarly named files.
Useful Stats methods:
sort_stats("tottime")orsort_stats("cumulative"). Other keys include"calls"and"filename". You can pass several keys to break ties.print_stats("mypackage")treats the string as a regular expression and keeps only rows whose file or function name matches. This is a good way to cut out standard-library noise.print_stats(10)keeps the first 10 rows. A float such as0.1keeps the first 10 percent. You can combine a pattern and a count, and the filters are applied in the order given.print_callers("slow_sum")shows which functions calledslow_sum.print_callees("main")shows which functionsmaincalled.
The .prof file can also be merged. stats.add("other.prof") combines data from several runs, which gives a more stable picture when the program's behavior varies between runs.
Making profiles useful
A profile is only as good as the workload it ran on. Follow these habits.
- Use a realistic input. A profile of a ten-row test file may show different hot spots than a profile of the real ten-million-row file, especially when an algorithm is quadratic.
- Profile the code that runs long enough to matter. If the whole script takes 0.2 seconds, startup and imports dominate the report.
- Keep a baseline. Save the first
.proffile with a date or commit hash, so you can compare after a change. - Compare wall-clock time with
perf_counteroutside the profiler. The profiler shows where to look, but your real success check is the unprofiled run getting faster.
Limits and gotchas
cProfile measures the interpreter's view of time, which leaves a few blind spots.
- Threads. A
Profileobject records the thread that enabled it. Work in other threads is not included unless you set up profiling in each thread, for example withthreading.setprofile. - Worker processes. Code that runs in
multiprocessingworkers is in separate processes and does not appear in the parent's report. Profile the worker function directly, with a single process, to see its cost. - Wall time and waiting. Time spent waiting on a network call, a disk read, or a lock is counted against the function that waited. A function with a high
tottimemay be idle rather than busy. Compare with CPU time before you decide that the code needs rewriting. - Profiler overhead. Small functions that are called very often are inflated. If a tiny helper is at the top of the report with millions of calls, check it with
timeiton its own before you act. - Import time. Imports run at the top of the script, and they appear in the report as many
<frozen importlib...>rows. Filter withprint_statsto ignore them, or profile only the main work with the context manager. - Recursion. In a recursive function,
cumtimeincludes the nested calls, and thencallsfield shows two numbers. Readtottimeinstead.
A short worked pass
Suppose python -m cProfile -o run.prof report.py finishes and you want to see the top ten functions by own time in your code only. You might run:
import pstats
stats = pstats.Stats("run.prof")
stats.sort_stats("tottime").print_stats("report", 10)Here "report" filters the rows to those whose path or name matches that pattern, and 10 limits the output to ten rows. If the top row is a function called parse_line with millions of calls, you have found a candidate. Call stats.print_callers("parse_line") to see who calls it so often. That points you to the loop that should change, which is usually an algorithm or data-structure fix before it is a micro-optimization.
Exercise
You run python -m cProfile -s cumulative app.py. The top row is main, with a cumtime of 12.0 seconds and a tottime of 0.01 seconds. A function load_rows has a cumtime of 11.5 seconds and a tottime of 0.3 seconds. A function normalize has a cumtime of 11.0 seconds and a tottime of 10.8 seconds. Where should you look first, and why? Which command would you run to see which functions call normalize?
Show answer
Look at normalize first. Its tottime of 10.8 seconds means almost all of its time is spent in its own code, not in functions it calls. main and load_rows have large cumtime values only because they call the expensive function. To see the callers, save the profile with -o app.prof, load it with pstats.Stats("app.prof"), and call print_callers("normalize").
Exercise
Why is the profile of a script that uses multiprocessing.Pool for its main work likely to look nearly empty, and what can you do about it?
Show answer
cProfile records only the process and thread where it is enabled. The pool's work runs in separate worker processes, so the parent's report mostly shows time spent waiting for results. To see the real cost, profile the worker function in a single process, for example by calling it directly in a loop under cProfile.Profile().