On this page
- Deterministic vs sampling profilers
- cProfile, pstats and snakeviz: the worked example
- py-spy: profile a running Python process
- pyinstrument: a call tree you can read
- line_profiler: find the slow line
- Scalene: CPU and memory in one pass
- memray: when the question is memory
- Profiling slow tests
- Which Python profiler should you use?
- What a profile does not tell you
- Putting profiles next to the call graph
- FAQ
The slow part of a Python program is rarely the part you would have guessed, so measure before you touch anything.
A Python profiler measures where a program spends its time, by function or by line, so you fix the part that is slow instead of the part you suspect. Deterministic profilers such as cProfile record every call. Sampling profilers such as py-spy look at the call stack many times a second and count what they see. Pick by the question: which function is hot, which line, which process, or which allocation.
For how to read the flame graph a sampling profiler draws, see flame graph: how to read one.
Deterministic vs sampling profilers
A deterministic profiler hooks every function call and return, so it knows exact call counts. A sampling profiler interrupts the program at a fixed rate and records the stack, so it knows where time went but only approximately.
The trade is overhead against detail. Hooking every call slows the program and inflates cheap functions that are called a lot, because the hook costs as much as the function. Sampling stays out of the way, which is why it is the usual choice for a live service, but a function that runs for less than the sampling interval can be missed.
| Deterministic | Sampling | |
|---|---|---|
| How it works | Hooks every call and return | Reads the stack at a fixed rate |
| Call counts | Exact | Not available |
| Short functions | Seen, but distorted by hook cost | May be missed |
| Needs a code change | No for cProfile, yes for line_profiler | No for py-spy, no for pyinstrument's CLI |
| Examples | cProfile, line_profiler | py-spy, pyinstrument, Scalene |
Scroll the table sideways to see every column.
The Python documentation says deterministic profiling "is not that expensive" for the statistics it gives you. Python 3.15 also adds a sampling profiler, profiling.sampling, which the docs point to for production debugging. See the Python profiling docs.
cProfile, pstats and snakeviz: the worked example
cProfile ships with Python, needs no install, and is the right first tool for any script you can run again. Run the script under it, save the result, and read it with pstats.
python -m cProfile -o out.prof report.py # save the profile
python -m cProfile -s cumtime report.py # or print a table sorted by cumulative time
-o writes the binary profile to a file, and -s sorts the table that is printed when you do not save. The printed table has one row per function:
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.002 0.002 4.810 4.810 report.py:1(<module>)
1 0.001 0.001 4.790 4.790 report.py:31(build_report)
50000 3.120 0.000 3.120 0.000 report.py:14(hash_row)
50000 0.410 0.000 1.650 0.000 report.py:22(parse_line)
The numbers above show the shape of the output, not a real run. The columns matter:
ncalls: how many times the function ran.tottime: time inside the function itself, subcalls excluded. This is the column that finds a hot function.cumtime: time including everything it called. This finds the expensive branch.percall: each of those divided by calls.
Sort by tottime to find where time burns, and by cumtime to find which entry point to look under. Load the saved file with pstats to re-sort without running again:
import pstats
p = pstats.Stats("out.prof")
p.strip_dirs().sort_stats("tottime").print_stats(10)
p.print_callers("hash_row") # who calls this function
print_callers answers the question the table cannot: why is this function called 50,000 times.
For a picture instead of a table, open the same file in snakeviz:
pip install snakeviz
snakeviz out.prof
It serves an interactive icicle chart in your browser, wide box means more cumulative time. To profile only part of a program, use cProfile.Profile() as a context manager around the block you care about and call print_stats on it.
py-spy: profile a running Python process
py-spy is a sampling profiler that runs outside your program, so you can point it at a process that is already running and change nothing. Its README describes it as extremely low overhead. It has three commands.
py-spy record -o profile.svg -- python myprogram.py # launch and profile, write a flame graph
py-spy record -o profile.svg --pid 12345 # attach to a running process
py-spy top --pid 12345 # live view, like top
py-spy dump --pid 12345 # print the current stack of every thread, once
record writes an SVG flame graph by default. --format switches to Speedscope or raw collapsed stacks. top shows the functions using the most time right now and updates as it samples. dump is the one to reach for when a process looks hung: it prints each thread's stack once, and --locals adds the local variables of each frame.
Four flags change what you see:
--subprocessesincludes child Python processes, which matters for multiprocessing and for servers that run workers such as gunicorn.--nativeincludes native extension frames, so time inside a C extension has a stack instead of one opaque line. Platform support varies, so check the README table.--idleincludes frames py-spy considers idle. Leave it off to see CPU work and turn it on to see waits.--gilkeeps only threads holding the GIL. It can hide activity in extensions that release the lock.
Attaching to a process you did not start needs privileges. On Linux that usually means running as root or relaxing the ptrace_scope setting, macOS always requires root, and containers need the SYS_PTRACE capability. Launching the program under py-spy with -- avoids the Linux restriction. Run py-spy record --help for the sampling rate and duration options on your version.
pyinstrument: a call tree you can read
pyinstrument is a sampling profiler that prints a call tree in the terminal, with the slow path expanded and the noise collapsed. It is the fastest way to answer "what is slow in this script" without reading a table.
pyinstrument report.py
pyinstrument -r html -o profile.html report.py
pyinstrument -r speedscope -o profile.speedscope.json report.py
pyinstrument -m mypackage.cli build
The default interval is 1 ms, set with -i in seconds. Use -r to pick the output: HTML for an interactive page, Speedscope for the speedscope viewer. For a block of code, use the API:
from pyinstrument import Profiler
profiler = Profiler()
profiler.start()
build_report()
profiler.stop()
profiler.print()
pyinstrument records wall-clock time, so waiting on a database or a socket shows up as time. That is what you want for a web request and a different number from CPU time. The docs cover async code, including a warning that FastAPI middleware only sees async routes, because sync routes run in a worker thread.
line_profiler: find the slow line
line_profiler times every line of the functions you mark, which is what you want after a function-level profile has named the suspect. It is deterministic and needs a code change: mark the functions to measure.
from line_profiler import profile
@profile
def hash_row(row):
...
Then run the script with the environment variable set:
LINE_PROFILE=1 python report.py
When the script ends it prints a per-line summary and tells you where it wrote the files. The older kernprof -lv report.py workflow still works. Mark only the one or two functions you already suspect, because timing every line of everything adds the overhead you were trying to avoid.
Scalene: CPU and memory in one pass
Scalene profiles CPU and memory per line in one run. It splits CPU time into Python time, native time (libraries written in C or C++) and system time (I/O and sleeping), which tells you whether a slow line is your code or a library call.
scalene run report.py
scalene run report.py --- --input data.csv # arguments after --- go to your program
scalene view --cli # print the results in the terminal
scalene view --html # write scalene-profile.html
scalene run -o results.json changes the output file. Memory is covered by the advanced options (scalene run --help-advanced lists --memory and --gpu), and the README says it also reports copy volume, which is useful for spotting NumPy and Python conversions. The project states its overhead is typically no more than 10 to 20 percent, with a 35 percent slowdown on one Pyperformance benchmark. See its README.
memray: when the question is memory
memray tracks every allocation, including native ones, and is the tool for "why is this process using 4 GB". The other profilers here measure time. memray measures memory.
memray run -o capture.bin myprogram.py
memray flamegraph capture.bin # an HTML flame graph of allocations
memray stats capture.bin # totals and the biggest allocators
memray run --native myprogram.py # include C and C++ frames
memray run --live myprogram.py # a live terminal view
memray run --follow-fork myprogram.py # track forked children, one capture file each
Use --native when the memory goes through NumPy, pandas or another extension, because otherwise the allocation shows up on the Python line that called it and the C frames stay hidden. The memray docs show a worked out-of-memory investigation with memray summary.
Profiling slow tests
If the slow thing is your test suite, you do not need a profiler first. pytest times every test and will list the slowest.
pytest --durations=10
That prints the ten slowest test phases (setup, call, teardown), so a slow fixture shows up as its own line. Fix those first. A test's time includes its fixtures, so a database fixture shared across a module is billed to the first test that needs it.
To profile the suite itself, run pytest under a profiler: py-spy record -o tests.svg -- pytest tests/unit shows where the time goes across all tests, including imports and fixtures. For code you want to track over time, write a benchmark with pytest-benchmark:
def test_hash_row(benchmark):
benchmark(hash_row, sample_row)
pytest --benchmark-only --benchmark-json=bench.json
pytest --benchmark-autosave
pytest --benchmark-compare
--benchmark-only skips the ordinary tests, --benchmark-json writes the full timings, and --benchmark-compare compares the current run with the last saved one.
Which Python profiler should you use?
The best Python profiler is the one that answers your question with the least change to the program. This table is the whole decision.
| Tool | Kind | Attach to a live process | Measures | Output |
|---|---|---|---|---|
cProfile | Deterministic | No | CPU time per function, call counts | .prof file, pstats table, snakeviz |
py-spy | Sampling | Yes, by PID | Where threads are, native frames with --native | SVG flame graph, Speedscope, raw stacks, live top |
pyinstrument | Sampling | No | Wall time per call path | Terminal tree, HTML, Speedscope |
line_profiler | Deterministic | No | Time per line of marked functions | Per-line table |
| Scalene | Sampling | No | CPU split Python, native, system; memory; copy volume | Terminal, HTML, JSON |
memray | Allocation tracing | Yes, memray attach <pid> on Linux and macOS | Every allocation | HTML flame graph, stats, tree |
pytest --durations | Timing | Not applicable | Duration per test phase | Terminal list |
Scroll the table sideways to see every column.
Choose by question:
- "Which function is slow in this script?"
cProfile, orpyinstrumentif you want a tree. - "Why is this production process slow right now?"
py-spy toporpy-spy dumpon its PID. - "Which line in this function is slow?"
line_profiler. - "Is it my code or a library?" Scalene's Python and native split, or
py-spy --native. - "Why is memory growing?"
memray. - "Why is the test suite slow?"
pytest --durations=10, thenpy-spyon the run.
What a profile does not tell you
A profile names a hot function and gives you a number. It does not tell you who calls it from where, which other hot spots share the same cause, or whether the code around it has a known slow shape such as a query inside a loop. That context sits in the structure of the code, and you rebuild it by hand each time.
A common case is a function that ranks first in a profile because it runs a database call per row. The profile shows the cost, and the fix is the N+1 query pattern. Seeing both together is faster than finding each separately.
Putting profiles next to the call graph
repowise ingests the profile as your profiler wrote it and joins each entry to a function in the index. The result carries the commit, the checkout and the workload it came from, so hot functions sit next to the call graph and the static performance findings, and an agent can read them. repowise evidence setup prints the profiler commands for your stack, you or your agent run them, and evidence add reads the file they wrote.
For Python it reads Speedscope JSON (from py-spy record --format speedscope or pyinstrument -r speedscope), collapsed stacks from py-spy record --format raw --full-filenames, pytest-benchmark JSON, and JUnit XML test reports. A profile needs a clock: pyinstrument output is wall-clock, and for py-spy you pass --value-kind.
repowise evidence setup --format json
py-spy record --format speedscope -o .repowise/app.speedscope.json -- python -m app.cli build
repowise evidence add .repowise/app.speedscope.json --workload "app build" --class entry_point --value-kind wall --commit $(git rev-parse HEAD)
repowise evidence add .repowise/pytest-bench.json --workload "pytest bench" --class benchmark --commit $(git rev-parse HEAD)
repowise evidence status
--workload names what ran, so an app build run and an app serve run keep separate histories. --class says how far the numbers reach: entry_point for a real command, benchmark for a benchmark run, unit_test for the test suite. Functions are ranked by their own time with waits excluded, and an entry that does not join to exactly one indexed function is skipped and counted by reason instead of guessed. This is the same method, with the profile kept and connected to the code. It works for Python alongside the other languages repowise reads, and it feeds the same view as the rest of code quality.
FAQ
- What is the best profiler for Python?
- For a script you can rerun, start with
cProfile, which ships with Python. For a process that is already running, usepy-spy, which attaches by PID without changing the code. For a readable call tree, usepyinstrument. None is best for every question, so pick by what you need to know. - What is the difference between cProfile and py-spy?
cProfileis deterministic: it hooks every call, so it gives exact call counts but must run inside your program.py-spyis a sampling profiler that runs outside it, so it can attach to a live process but gives approximate time and no call counts.- How do I profile a running Python process?
- Use
py-spy record -o profile.svg --pid <pid>to record a flame graph,py-spy top --pid <pid>for a live view, orpy-spy dump --pid <pid>to print every thread's current stack. On Linux you usually need root or a relaxedptrace_scope, and containers need theSYS_PTRACEcapability. - How do I find slow tests in pytest?
- Run
pytest --durations=10to list the ten slowest test phases, including fixture setup. To see where the time goes inside the suite, run pytest underpy-spy record -- pytest tests/unit. For functions you want to track over time, usepytest-benchmark. - How do I profile Python memory use?
- Use
memray:memray run -o capture.bin myprogram.py, thenmemray flamegraph capture.binormemray stats capture.bin. Add--nativeif the memory goes through C extensions such as NumPy. Scalene also reports memory per line alongside CPU. - Can repowise read a Python profile?
- Yes.
repowise evidence addreads Speedscope JSON, collapsed stacks, pytest-benchmark JSON and JUnit XML, joins each entry to a function in the index with its commit and workload, and shows hot functions beside the call graph and static performance findings.



