Locate Hot Functions with cProfile and pstats
Core idea
A deterministic profiler records function calls and time spent. cProfile.Profile can profile a bounded workload; pstats.Stats organizes its records. Internal time excludes subcalls, while cumulative time includes them. Inspect call counts as well as timing, and confirm any proposed optimization with an unprofiled benchmark because profiling changes execution costs.
import cProfile, pstatsdef unit(n): return n * 2def workload(): return sum(unit(i) for i in range(5))p = cProfile.Profile()answer = p.runcall(workload)stats = pstats.Stats(p)key = next(k for k in stats.stats if k[2] == 'unit')print(answer, stats.stats[key][1])The Stats record contains total calls at index one; the helper executes five times.
Expected output:
20 5Sort a captured report
import cProfile, pstats, iodef work(): return sum(range(30))p = cProfile.Profile(); result = p.runcall(work)buf = io.StringIO()pstats.Stats(p, stream=buf).sort_stats('cumulative').print_stats(5)print(result, 'work' in buf.getvalue())The report is ordered by cumulative time; its timing values and ranking are environment dependent.
Expected output:
435 TrueCommon mistake
A large cumulative time may reflect an expensive child rather than slow code in the caller. Never conclude universal speed from profiling percentages or compare profiles as if they were raw benchmarks.
Practice
Profile a function with repeated parsing and aggregation. Inspect call counts, internal and cumulative time; optimize one hotspot and rerun an unprofiled measurement.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CProfile and pstats
Check your understanding of cprofile and pstats.
What is printed?
import cProfilep=cProfile.Profile()print(p.runcall(sum,[1,2,3]))What is printed?
import cProfile,pstatsdef f(): return 1p=cProfile.Profile();p.runcall(f)print(any(k[2]=="f" for k in pstats.Stats(p).stats))What does cumulative time include?
Why benchmark again without profiling?