Find a slow Python function with cProfile and pstats
Use cProfile and pstats to find repeated work in a Python script, verify an optimization, and compare timings without the profiler.
When a Python script feels slow, use cProfile to record how often its functions run and how much time they account for. Then use pstats to sort the report and see which callers are responsible for the work. Both modules come with Python. Python profiler documentation
In this example, a report parses the same rows once for every product. You’ll use the profile to find the repeated work, change the report to process each row once, and check that every total still matches.
Create a slow but reproducible report
Save this as slow_report.py in an empty directory. It uses 20,000 generated rows across 80 product IDs.
def make_rows():
return [f"sku-{i % 80:03d},{i % 7 + 1}" for i in range(20_000)]
def parse_row(row):
sku, quantity = row.split(",", 1)
return sku, int(quantity)
def totals_by_sku(rows):
skus = {parse_row(row)[0] for row in rows}
totals = {}
for sku in skus:
total = 0
for row in rows:
row_sku, quantity = parse_row(row)
if row_sku == sku:
total += quantity
totals[sku] = total
return totals
if __name__ == "__main__":
totals = totals_by_sku(make_rows())
print(len(totals), sum(totals.values()))
Capture and inspect a profile
Run these commands from the directory containing the script, using the same Python interpreter for both. The first command still prints the report’s output, 80 79997. The -o option saves the profiling statistics to slow.pstats. The second command opens that file in the interactive report viewer. Saving profiler statistics
python3 -m cProfile -o slow.pstats slow_report.py
python3 -m pstats slow.pstats
Enter these commands at the pstats prompt.
sort cumulative
stats 8
sort time
stats 8
callers parse_row
quit
Read the columns this way. Python profile report columns
| Column | What it tells you |
|---|---|
ncalls |
How many times the function was called. A recursive function can show total calls followed by primitive calls, as in 3/1. |
tottime |
Time spent in the function itself, excluding its callees. Sort by time to surface functions with high self time. |
cumtime |
Time attributed to the function and the functions it calls. Sort by cumulative to find expensive branches of the workload. |
Start with cumulative time to find your own functions near the top of the report. A wrapper such as <module> often has high cumulative time because it encloses the whole run. Look at the cost and call count of the functions underneath it. Here, parse_row runs 1,620,000 times for just 20,000 input rows. It runs once per row to collect the product IDs, then once per row for each of the 80 products. The callers report points back to that workload.
Remove the repeated work and compare
Save this as fast_report.py beside the first script. It uses the same parser and adds each quantity to its product’s total as it reads the row.
from slow_report import make_rows, parse_row
def totals_by_sku(rows):
totals = {}
for row in rows:
sku, quantity = parse_row(row)
totals[sku] = totals.get(sku, 0) + quantity
return totals
if __name__ == "__main__":
totals = totals_by_sku(make_rows())
print(len(totals), sum(totals.values()))
Check the full result. Matching the product count and grand total alone could miss a quantity assigned to the wrong product.
python3 - <<'PY'
from fast_report import totals_by_sku as fast
from slow_report import make_rows, totals_by_sku as slow
rows = make_rows()
assert fast(rows) == slow(rows)
print("All product totals match.")
PY
Profile the new version and print the parse_row entry from both captures. The Python API is useful when you want the same report for every run. The pstats reporting API
python3 -m cProfile -o fast.pstats fast_report.py
python3 - <<'PY'
from pstats import SortKey, Stats
for path in ("slow.pstats", "fast.pstats"):
print(f"\n{path}")
Stats(path).strip_dirs().sort_stats(SortKey.CUMULATIVE).print_stats("parse_row")
PY
The new profile shows 20,000 calls to parse_row, one for each row. The exact timings depend on your machine and interpreter. The call count explains what changed.
Time the change without profiling
Profiling adds overhead. For a timing comparison, reuse the same input and time each function separately with timeit. The setup lines build the input outside the timed statement. Python timeit documentation
python3 -m timeit -r 3 \
-s 'from slow_report import make_rows, totals_by_sku' \
-s 'rows = make_rows()' 'totals_by_sku(rows)'
python3 -m timeit -r 3 \
-s 'from fast_report import totals_by_sku' \
-s 'from slow_report import make_rows' \
-s 'rows = make_rows()' 'totals_by_sku(rows)'
Compare the reported time per loop on the same machine. For your own script, profile a representative input, fix the repeated work you can explain, and verify the result before interpreting the timing.