Sub topic 10
Profiling running programs with a sampling profiler
This chapter assumes you can read cProfile output (tottime and cumulative time) and are comfortable with a terminal and pip. A sampling profiler answers the same question as cProfile, "where does the time go?", but it works differently. It can attach to a program that is already running, and it adds very little overhead.
How sampling differs from deterministic profiling
cProfile is a deterministic profiler. It hooks every function call and return, and it records exact call counts and timings. That precision has a cost. Programs with many small function calls can run noticeably slower under cProfile, and the distortion can move the hot spot.
A sampling profiler does not watch every call. At a fixed rate, for example 100 times per second, it looks at what the program is doing and records the current call stack. Over thousands of samples, a function that is on the stack 40% of the time shows up in about 40% of the samples.
| Property | cProfile (deterministic) | Sampling profiler (py-spy) |
|---|---|---|
| What it records | Every call and return | The stack, at regular intervals |
| Call counts | Exact | Not available |
| Overhead | Often large for call-heavy code | Small, since the profiler runs outside the program |
| Attach to a running process | No | Yes, by process ID |
| Needs code changes or a restart | Yes, or a new launch under `-m cProfile` | No |
| Short-lived functions | Always seen | May be missed |
A sampler in about 25 lines
The mechanism is simple enough to build yourself. This script starts a background thread that wakes every few milliseconds and uses sys._current_frames() to see which function the main thread is executing. It counts the function names and prints the shares.
import collections
import sys
import threading
import time
def sample_main_thread(counts, stop, interval=0.005):
main_id = threading.main_thread().ident
while not stop.is_set():
frame = sys._current_frames().get(main_id)
if frame is not None:
counts[frame.f_code.co_name] += 1
time.sleep(interval)
def hot(n):
total = 0
for i in range(n):
total += i * i
return total
def cold(n):
return sum(range(n))
def main():
for _ in range(100):
hot(200_000)
cold(200_000)
if __name__ == "__main__":
counts = collections.Counter()
stop = threading.Event()
sampler = threading.Thread(target=sample_main_thread, args=(counts, stop))
sampler.start()
main()
stop.set()
sampler.join()
total = sum(counts.values())
for name, n in counts.most_common():
print(f"{name:8s} {n:5d} samples {100 * n / total:5.1f}%")hot runs a Python-level loop, while cold uses the built-in sum, which loops in C. The report should show hot with most of the samples, and the exact numbers differ from run to run. That variation is a property of sampling, and the next sections return to it.
This toy sampler is limited. It runs inside the target process and competes for the GIL (Global Interpreter Lock). It only sees Python frames, and it only watches one thread. Real tools avoid these problems by reading the process's memory from outside.
Using py-spy
py-spy is a sampling profiler written in Rust. It runs as a separate process and reads the target's memory, so the target needs no changes. Install it with pip.
pip install py-spyThere are three main commands.
# 1. Live view, like `top`, for a running process
py-spy top --pid 12345
# 2. Record a flame graph from a running process for 30 seconds
py-spy record --pid 12345 --duration 30 -o profile.svg
# 3. Launch a script under the profiler
py-spy record -o profile.svg -- python myscript.pyA third command, py-spy dump --pid 12345, prints the current stack of every thread once. It is the fastest way to answer "what is this process stuck on right now?" when a service hangs.
py-spy top shows a live table. For each function it reports the time spent running the function itself (own time) and the time including everything it calls (total time). These two columns match tottime and cumulative time in cProfile, so you can read the table with the skills from the earlier chapter.
Reading a flame graph
py-spy record writes an SVG flame graph by default. Open it in a browser.
- Each box is a function. The box below it is its caller, and the boxes above it are the functions it calls.
- Width is the share of samples where that function was on the stack. Left-to-right position has no meaning, because boxes are sorted alphabetically.
- A wide box with a flat top means the function is busy itself. A wide box with many narrow boxes above it spends its time in its callees.
Look for the widest boxes with nothing wide above them. That is the same hunt you did with tottime, in visual form.
For large profiles, --format speedscope writes a file that you can load at speedscope.app, where you can zoom and switch views. --format raw writes plain text lines of stack and count. You can post-process it with your own scripts.
Useful options
| Option | Effect |
|---|---|
| `--rate N` | Samples per second. The default is 100. |
| `--duration S` | Stop after S seconds. |
| `--idle` | Include threads that are waiting, for example on I/O or locks. They are hidden by default. |
| `--gil` | Keep only samples from the thread that holds the GIL. |
| `--native` | Include frames from C and C extension code, such as NumPy internals. |
| `--subprocesses` | Also profile child processes. |
Reading sampled results correctly
Own time versus total time
The rules from cProfile still apply. A function with high total time but low own time is a caller. The cost is further down the stack. The fix belongs in the callee, or in how often the caller invokes it.
Statistical noise
Each sample is one observation, so small percentages are unreliable. At 100 samples per second, a 10-second run gives about 1,000 samples. A function that shows 1% has about 10 samples behind it, and a rerun might show 0.5% or 1.8%. Trust the large boxes. For small ones, record for longer or raise --rate. Do not read a difference of a few samples as meaningful.
Waiting is invisible by default
By default py-spy skips idle threads. A program that spends 90% of its time waiting on the network will show a profile of only the 10% that uses the CPU. That is correct for CPU tuning, but it hides latency problems. If the question is "why is this request slow?", run with --idle and look for wide boxes in functions such as socket.recv, time.sleep, or Lock.acquire.
Missing counts
A sampling profiler cannot tell you that a function was called 2 million times. It can only tell you that the function was on the stack in some fraction of samples. If you suspect a function is called too often, use cProfile for the count. A function that takes 1 microsecond per call and runs for 10 seconds in total will show up in both tools, because the sample count tracks accumulated time.
Common errors
- Permission denied when attaching. On Linux, py-spy needs permission to read another process's memory. Run it with
sudo, or as the same user with a permissiveptrace_scopesetting. On macOS it must run as root. - Containers. Inside Docker, attaching fails unless the container has the
SYS_PTRACEcapability. In Kubernetes, add it to the pod's security context in a development environment, and avoid doing so in production without review. - Profiling the wrong process. Servers such as gunicorn start a parent and several workers. Attaching to the parent shows almost nothing. Use
psto find a worker's PID, or pass--subprocesseswhen launching under py-spy. - Profiles that are too short. A script that finishes in half a second yields about 50 samples. Run a larger input, loop the workload, or increase
--rate. - Blaming Python for work done in C. If one function in a flame graph is wide but has nothing above it, the time may be inside a C extension. Add
--nativeto see which native functions are running.
When to choose which tool
Use cProfile when you need exact call counts, or when the program is small and starts from a script you control. Use a sampling profiler when the process is already running, when it is a long-lived service, when cProfile's overhead distorts the result, or when you need to see native frames or waiting threads. Both tools point at the same kind of target, a hot function, and the fixes from the following chapters apply either way.
Exercise
Your web service is slow in production, and you cannot restart it. A py-spy top --pid view shows render_page with 5% own time and 80% total time. What does this tell you, and what should you do next?
Show answer
render_page is mostly a caller. It does little work itself, and about 75% of the time is spent in functions it calls. Record a flame graph with py-spy record --pid <PID> --duration 30 -o profile.svg and look at the boxes directly above render_page. The widest box with nothing wide above it is the function to examine.
Exercise
A flame graph from py-spy record for a script that downloads many files shows only a tiny amount of time in the download function, yet the script takes 5 minutes. Why, and how do you check?
Show answer
By default py-spy hides idle threads, and waiting on the network is idle time. The samples therefore cover only the small CPU portion. Rerun with --idle and the download function should appear as a wide box, probably in a call such as socket.recv.