Sub topic 4
Reading profiles: tottime, cumulative time, and callers
This chapter assumes you can run a script under cProfile (covered in the previous chapter) and are comfortable with functions, list comprehensions, and generators. It covers how to read the table that profiler produces, so you can tell which function is slow and which one only calls the slow function.
What a profile row tells you
cProfile is a deterministic profiler. It hooks every function call and return, and records how many times each function ran and how long it took. The pstats module turns those records into a table with one row per function.
| Column | Meaning |
|---|---|
| `ncalls` | Number of calls. For recursive functions it shows `total/primitive`, such as `21891/1`. |
| `tottime` | Seconds spent inside the function's own code, excluding time in functions it called. |
| `percall` (first) | `tottime` divided by `ncalls`. |
| `cumtime` | Seconds from entering the function to leaving it, including everything it called. |
| `percall` (second) | `cumtime` divided by the number of primitive (non-recursive) calls. |
| `filename:lineno(function)` | Where the function is defined. |
The two time columns answer different questions.
tottimeanswers "where is the time spent?" A function with a hightottimeruns slow code itself: a tight loop, heavy arithmetic, or a slow built-in.cumtimeanswers "which call chain is expensive?" A function with a highcumtimeand a lowtottimeis mostly a coordinator. It is expensive because of what it calls.
A program to profile
The following script has a clear structure: main calls load and report, load calls parse, and report calls score. It profiles only the work inside the with block, then prints four views of the same data.
import cProfile
import pstats
def parse(line):
return [int(x) for x in line.split(",")]
def load(lines):
return [parse(line) for line in lines]
def score(row):
total = 0
for value in row:
total += value * value
return total
def report(rows):
return sorted(score(row) for row in rows)
def main():
lines = [",".join(str(i) for i in range(50)) for _ in range(5_000)]
rows = load(lines)
return report(rows)
with cProfile.Profile() as profiler:
main()
stats = pstats.Stats(profiler).strip_dirs()
stats.sort_stats("tottime").print_stats(6)
stats.sort_stats("cumulative").print_stats(6)
stats.print_callers("score")
stats.print_callees("main")Two details about the pstats.Stats calls matter here:
strip_dirs()removes directory prefixes from file names so rows fit on screen. Call it beforesort_stats, because stripping can change the ordering.- Each method returns the
Statsobject, so you can chain calls. The numbers on your machine will differ from anyone else's. Compare the relative sizes and the ordering, not the absolute seconds.
Sorting by tottime
The first table, sorted by tottime, is your list of hot spots. In this program you should see score near the top, since it runs a Python loop 250,000 times. You should also see the comprehension frames in parse and the built-in split and join methods.
Read the top rows with these questions:
- Is one row far larger than the rest, or is the time spread over many rows? A single dominant row is a good target. A flat profile means no single fix will give a large gain, and you should look at the algorithm instead.
- Is the row your code or a built-in? A row like
{method 'split' of 'str' objects}is C code that you cannot edit. You can only call it less often or on less data. - Is
ncallshuge whilepercallis tiny? Then the cost is the number of calls, and the fix is usually to call less often, for example by batching or caching.
Sorting by cumulative time
The second table, sorted by cumulative, shows the call chains. main is at or near the top because it contains everything. load and report follow, then parse and score. Its tottime is tiny compared to its cumtime, because main itself does almost nothing except set up and call.
Use this view to choose where to look first. If report has a larger cumtime than load, the next question is which of its callees is responsible.
The following diagram shows the same structure for this program. Each box shows which time column carries the cost.
Finding callers and callees
A function name alone often does not tell you where to make the change. If score is slow, the question is who calls it and how often. print_callers answers that, and print_callees gives the reverse: what a function spends its cumulative time on.
stats.print_callers("score")
stats.print_callees("main")Both methods take a restriction. A string is treated as a regular expression matched against the filename:lineno(function) text, an integer limits the number of rows, and a float between 0 and 1 keeps that fraction of rows. The same restrictions work with print_stats. For example, print_stats("parse|load") shows only rows matching either name.
The callers output shows an extra detail. In this program, the caller of score is not report. It is <genexpr>, the generator expression inside report that sorted consumes. Generators and comprehensions have their own frames, so they appear as separate rows and sit between the function you wrote and the function it calls.
Gotchas when reading a profile
Comprehension rows depend on the Python version
Before Python 3.12, a list comprehension runs in its own frame and shows up as <listcomp>. Since 3.12, list comprehensions are inlined into the enclosing function (PEP 709), so their time lands in the function's tottime and no <listcomp> row appears. Generator expressions still have their own <genexpr> frames in all versions. If a tutorial or a colleague's output shows rows you do not have, check the Python version first.
Built-in types may not appear as rows
The profiler records calls to built-in functions and methods, such as sorted or str.split. Constructor calls on types, such as int(x), may not get a row of their own. Their time is then charged to the calling function's tottime. If a function seems slower than its own code explains, a hidden constructor call is a common cause.
Profiling overhead is not uniform
cProfile adds a fixed cost to every call and return. Functions that are called millions of times with tiny bodies look more expensive in the profile than they are in a normal run. A profile can also change the ranking: a function that is 10% of the real time may show up as 30%. Treat the profile as a pointer to where to look, then confirm the fix with timeit or perf_counter on the unprofiled code.
Recursion and the two percall columns
For recursive functions, ncalls shows total/primitive. The second percall divides cumtime by the primitive count, so it reflects the cost of one top-level call, not one recursive step. The profiler also avoids double-counting nested recursive time in cumtime.
Short runs are noisy
A profile of a run that lasts a few milliseconds has too little data to rank rows reliably. Profile a run long enough that the main rows stand out, and run it more than once if two rows are close.
Saving and reloading profiles
For longer programs, save the profile and analyze it later without rerunning the code. This lets you try different sort orders and restrictions on the same data.
python -m cProfile -o out.prof myscript.py
python -c "import pstats; pstats.Stats('out.prof').strip_dirs().sort_stats('tottime').print_stats(10)"From inside Python, profiler.dump_stats("out.prof") writes the same file. pstats.Stats also accepts several files and merges them, which helps when you collect profiles from several runs.
A reading routine
- Sort by
cumulativeand find the top-level call chain that dominates the total. This tells you which part of the program matters. - Sort by
tottimeand find the function inside that chain with the largest own time. - Use
print_callerson that function to see who calls it and how often. A fix is often in the caller, which can call less. - Use
print_calleeson the expensive parent to check where its remaining time goes. - Change one thing, re-measure, and compare against the original profile.
Exercise
A function build has tottime of 0.02 s and cumtime of 4.1 s. A function tokenize has tottime of 3.6 s and cumtime of 3.7 s. Which should you optimize first, and why?
Show answer
Start with tokenize. Its tottime shows that 3.6 s is spent in its own code, which is where the work happens. build has a large cumtime only because it calls other functions, likely including tokenize. Its own code takes just 0.02 s. Use print_callers("tokenize") to see whether build calls it too often.
Exercise
You profile a program and print_stats shows <genexpr> as the caller of your function score, not the function that contains the generator expression. Why, and how do you find the enclosing function?
Show answer
A generator expression runs in its own frame, so the profiler records it as a separate function, <genexpr>, and that frame is the one that calls score. To find the enclosing function, run print_callers("genexpr") or look at the line number in the <genexpr> row, which points to the line in the source where the generator is written.