Sub topic 10
Profiling running programs with a sampling profiler
This chapter assumes you can run cProfile and read tottime and cumulative columns, and that you can use pip and a terminal. Here you learn what a sampling profiler is, when it beats cProfile, and how to use py-spy.
How sampling differs from deterministic profiling
cProfile is a deterministic profiler. It hooks every function call and return, so it sees every call but slows the program down, sometimes by a large factor for code with many small calls. You also have to start the program under the profiler.
A sampling profiler works differently. It looks at the program's call stack many times per second (for example 100 times) and records which function is running each time. Functions that appear in many samples are where time goes. It counts no individual calls, so it adds little overhead, and it can be pointed at a program that is already running.
| Property | cProfile (deterministic) | py-spy (sampling) |
|---|---|---|
| Overhead | Moderate to high | Low |
| Needs code changes or a restart | Yes | No |
| Exact call counts | Yes | No |
| Can attach to a running process | No | Yes |
| Short functions | Seen precisely | Can be missed |
Installing and recording with py-spy
py-spy is a sampling profiler for Python written in Rust. It reads the memory of the Python process from outside, so the target program needs no changes.
pip install py-spySave this as work.py. It has one obvious hot spot:
import time
def parse(line):
return [int(x) for x in line.split(",")]
def slow_total(rows):
total = 0
for row in rows:
for value in row:
total += value * value
return total
def main():
lines = ["1,2,3,4,5,6,7,8,9,10"] * 200_000
rows = [parse(line) for line in lines]
print(slow_total(rows))
time.sleep(1)
if __name__ == "__main__":
main()Record a profile and write a flame graph:
py-spy record -o profile.svg -- python work.pyOpen profile.svg in a browser. A flame graph shows the call stack with the entry point at the bottom. Each box is a function, and its width is the share of samples where that function was on the stack. Wide boxes are the places to examine. Time spent in time.sleep does not appear by default, because py-spy skips idle threads. Add --idle to include it.
Attaching to a running process
The main advantage of a sampling profiler is that you can inspect a program you did not start under a profiler, such as a stuck worker or a service in production.
py-spy top --pid 12345
py-spy dump --pid 12345top shows a live table of the functions using the most time, like the Unix top command. dump prints the current call stack of every thread once, which is useful for answering "what is this process doing right now?"
Reading the result
Treat a flame graph the way you treated cumulative time in cProfile. A wide box means the function, or something it calls, was on the stack often. A wide box with narrow boxes above it means the time is spent in that function's own code. Many narrow boxes above it means the time is spread among callees.
In work.py, expect main to be the widest box, with the list comprehension that calls parse and the nested loops in slow_total as its main children. That tells you where to look first. Then use the earlier tools to fix it: a better algorithm or data structure, or NumPy for the numeric loop.
When to choose which profiler
- Use
timeitorperf_counterto compare two small snippets. - Use
cProfilewhen you can run the script yourself and need exact call counts. - Use
py-spywhen overhead matters, when you cannot restart the process, or when the program is long-running.
Exercise
A web service is slow only in production, and you cannot restart it. Which tool do you use first, and which command shows what every thread is doing at this moment?
Show answer
Use a sampling profiler such as py-spy, because it attaches to a running process with low overhead and needs no code changes. The command py-spy dump --pid <PID> prints the current call stack of every thread. py-spy top --pid <PID> gives a live view of the busiest functions.
Exercise
Why might a sampling profiler fail to show a function that cProfile reports was called 5,000 times?
Show answer
Each call may be so short that the sampler rarely catches it running. Sampling is statistical and only sees functions that are on the stack at the moments it samples. cProfile hooks every call, so it records them all, at the cost of higher overhead.