Lesson · Performance & Profiling
Profiling
75 min readProfiling
Profiling shows where a program actually spends time. Function-level profiles, call counts, cumulative time, and memory observations help you choose the next optimization target.
Learning goals
- Run a function under
cProfilewithProfile().runcalland get statistics without editing the function. - Name what the
pstatscolumns count:ncalls,tottime,cumtime, and the twopercallcolumns. - Choose the sort key for a question:
cumulativefor slow call paths,tottimefor time owned by a function's own body. - Explain why a profile's ranking depends on the workload, so a toy input can point at the wrong target.
- State what a memory profile adds that a time profile cannot show.
Mental model
The table is the deliverable, and the sort key is the question: cumtime finds slow call paths including descendants, while tottime finds functions that spend time in their own body. Neither column decides anything alone, so read call counts next to times before selecting a target.
Mental model
read it top to bottom
run code under cProfile
↓ records per-call data
pstats.Stats(profiler)
↓ sort_stats("cumulative" or "tottime")
read the table: ncalls / tottime / cumtime / percall
↓
pick the next optimization targetCore idea
Profiling replaces guessing with attribution: it runs the program under a recorder that counts calls and times each function, then lets you rank those functions as a table. The central distinction is between time a function spends in its own body (tottime) and the total time of the subtree it roots (cumtime), because the second includes everything it calls. Choose the sort key by the question, and remember that the profile describes the workload you ran, not all workloads.
cProfile
cProfile is a deterministic function profiler included with Python. It reports call counts and timing data that help identify expensive call paths.
pstats
pstats reads the raw data a profiler collected and turns it into tables you can sort and filter, so you can answer one question at a time instead of scanning a flat dump. You build pstats.Stats(profiler), choose a sort key such as "cumulative" or "tottime" with sort_stats, and print rows with print_stats; an argument like print_stats(5) keeps the output to the top rows. It does not re-run anything, so the statistics reflect exactly the calls the profiler recorded.
Call counts
Profiler statistics help separate frequently called code from individually expensive code. Cumulative time is useful for call trees because it includes work performed by descendants.
Cumulative time
Profiler statistics help separate frequently called code from individually expensive code. Cumulative time is useful for call trees because it includes work performed by descendants.
Hot paths
Profiler statistics help separate frequently called code from individually expensive code. Cumulative time is useful for call trees because it includes work performed by descendants.
Memory profiling concepts
A memory profile answers a different question from a time profile: it tracks allocations, such as the peak amount of memory live at once or which lines created the objects still being held. Python's tracemalloc samples allocations and reports the top allocation sites by size, which is the tool you reach for when a program slows down because it is paging or its memory keeps growing. A time profiler shows none of this, because a function can hold most of the memory while burning almost no CPU.
Walkthrough
cProfile.Profile()creates the profiler object, andprofiler.runcall(workload)executes the function under it, recording one entry per call; the loop insideworkloadruns with no source change, which is the point ofruncall.pstats.Stats(profiler)wraps the recordings, andsort_stats("cumulative")orders the rows by the total time spent in each function including its callees, soprint_stats(5)lists the five heaviest call paths.- In the output,
workloadshows one call whosecumtimecovers the hundred thousand iterations; thencallsandpercallcolumns are what separate a function called once and expensively from one called constantly and cheaply. - Predict before running: whether
workloadstays first when you sort by"tottime"instead of"cumulative", and why the distinction matters here where the loop runs inline.
Experiments to try
- Move the loop body into a separate
square_uphelper and re-profile; note wherencallslands, wheretottimemoves, and whatworkloadnow owns. - Sort the same
Statsobject by"tottime", then"ncalls", and compare the top rows; write one sentence per sort key describing the question it answers. - Call
print_stats(1),print_stats("workload"), andprint_stats()on the same statistics and describe what each form is useful for. - Run
tracemallocaround a function that builds a large list and report the peak allocation; contrast that answer with what the profile said, using the question each tool answers.
Common mistakes
- Reading
tottimeas "this function plus everything it calls":tottimeexcludes callees, so a cheap-looking wrapper around an expensive function carries its cost in thecumtimerow instead. - Optimizing the top row by time alone when the real workload calls it once: a single heavy call and a million tiny calls need different fixes, so read
ncallsnext tocumtime. - Profiling a toy input and trusting the ranking: call overhead and cache behavior change with size, so a profile of 100 items can order functions differently from production data.
- Expecting the profiler to find code that never ran:
cProfilereports what executed, so a slow path the workload never triggers is invisible in the table.
Practice: Easy
- Run the worked example and copy the full table; label each column with what it counts.
- Split the loop body into a helper
square_up(n)and re-run the profile; record the helper'sncallsandtottimeand explain both numbers. - Change
print_stats(5)toprint_stats("workload")and then toprint_stats(1); write what each output includes and when you would use it.
Practice: Medium
- Write a script with three functions that differ in call pattern (one expensive call, many cheap calls, a deep call chain) and profile it; from the table alone, rank the three by time owned and by subtree time.
- Wrap the example in
def main():and profilemain; compare itscumtimewith the sum of its children's rows and explain any difference. - Profile a script with two hot spots, double the input size, and profile again; describe which row's rank changed and why.
Practice: Hard
- Build a workload where sorting by
tottimeand sorting byncallsdisagree about the top row; document both tables and explain the disagreement in terms of what each column measures. - Take a slow function you already know from your own code: predict its top
cumtimerow before profiling, then profile it and explain every row that surprised you. - Benchmark a script with
perf_counter, then profile the same script; describe one question the total time answered, one it could not, and how the table filled the gap.
Lesson checklist
- I can profile a function without editing it and print the top rows with
pstats. - I can explain the difference between
tottimeandcumtimeusing the worked example's rows. - I can choose a sort key, and a print count, for a stated question.
- I can name one way profiler output can mislead: a toy input, profiler overhead, or code paths that never ran.
Remember
Profiling attributes time to functions: `cProfile` records every call, and `pstats` turns those recordings into sortable tables. The two columns that matter most answer different questions, `tottime` for time a function spends in its own body and `cumtime` for the whole call path it roots, and the workload you profile decides whether those rankings transfer. Memory profiling is a separate instrument for a separate question: how much is allocated and where it is still held.
Interview angles
What is the main purpose of **cProfile**?+
cProfile is a deterministic function profiler included with Python. It reports call counts and timing data that help identify expensive call paths.
What should you pay attention to when using **pstats**?+
pstats reads the recordings a profiler collected and turns them into sortable tables: build pstats.Stats(profiler), choose a key with sort_stats, and limit rows with print_stats. It does not re-run the code, so the table shows exactly the calls the profiler recorded.
How does **Call counts** fit into this lesson?+
Profiler statistics help separate frequently called code from individually expensive code. Cumulative time is useful for call trees because it includes work performed by descendants.
Why can a cheap-looking function still be the real cost center in a profile?+
Its own body may do almost nothing while the functions it calls do the work, and that time appears in its cumtime row rather than its tottime. Sort by cumtime to find heavy call paths, then read ncalls beside it to plan the fix.