Skip to main content

Dev tools and workflow · Advanced · 18 min

Profile slow code and read a flame graph

By Padding · Updated 18 Nov 2026
Python 3.15 · py-spy 0.4.4 · hyperfine 2.0.0 (checked on python:3.15-slim)

You will time a slow Python report with hyperfine, find its hot function with cProfile and a py-spy flame graph, fix it, and prove the speed-up with numbers.

On this page

When code is slow, the tempting move is to guess which line is to blame and rewrite it. Guesses are wrong often enough that the rewrite can cost a day and change nothing. Profiling replaces the guess with a measurement: it tells you where the time actually goes, so you change one function and leave the rest alone.

You will work on a small sales report script that is slow on purpose. You will time it with hyperfine, a benchmarking tool that runs a command several times and reports the spread. You will profile it two ways: cProfile, the profiler built into Python, which counts every function call, and py-spy, a sampling profiler that looks at the running program about a hundred times a second and draws the result as a flame graph. Then you fix the hot function and use hyperfine again to show the change worked.

The habit carries beyond Python. Measure first, profile second, change one thing, measure again. If your users reach your service over prepaid mobile data on low-end Android phones, every second the server spends is a second they wait with the screen open, so this loop pays off quickly.

Step 1 · Set up a practice project

Create a throwaway folder with its own virtual environment and install py-spy into it. py-spy is written in Rust and ships as a ready-built binary inside the Python package, so there is nothing to compile:

Bash
mkdir -p ~/profile-demo
cd ~/profile-demo
uv venv --python 3.15
uv pip install "py-spy==0.4.4"
source .venv/bin/activate
python --version
py-spy --version

Run the later commands in this same terminal, with the environment active. If you open a new terminal, cd ~/profile-demo and run source .venv/bin/activate again.

Now write the script you will speed up. It invents 5,000 customers and 10,000 orders (the same ones every time, because the random generator has a fixed seed), adds up the order values per country and prints a table:

Bash
cat > report.py <<'PY'
import random
from collections import defaultdict

COUNTRIES = ["Nigeria", "Kenya", "Ghana", "Egypt", "South Africa", "Brazil", "India", "Germany"]


def make_data(n_customers=5000, n_orders=10000, seed=7):
    rng = random.Random(seed)
    customers = [{"id": i, "country": rng.choice(COUNTRIES)} for i in range(n_customers)]
    rng.shuffle(customers)
    orders = [(rng.randrange(n_customers), rng.randint(500, 50000)) for _ in range(n_orders)]
    return customers, orders


def find_customer(customers, customer_id):
    for customer in customers:
        if customer["id"] == customer_id:
            return customer
    raise KeyError(customer_id)


def total_by_country(customers, orders):
    totals = defaultdict(int)
    for customer_id, amount_cents in orders:
        customer = find_customer(customers, customer_id)
        totals[customer["country"]] += amount_cents
    return totals


def format_report(totals):
    rows = sorted(totals.items(), key=lambda row: row[1], reverse=True)
    return "\n".join(f"{country:<14}{cents / 100:>14,.2f}" for country, cents in rows)


def main():
    customers, orders = make_data()
    print(format_report(total_by_country(customers, orders)))


if __name__ == "__main__":
    main()
PY
python report.py

Do not fix anything yet, even if you can already see the problem. The point is to practise finding it with tools, because in real code the slow part is rarely this short.

Check it worked

python --version prints Python 3.15 followed by a patch number, and py-spy --version prints py-spy 0.4.4. The script prints eight lines, one per country, each with a total such as Nigeria followed by a number with two decimal places. It takes about a second on a typical laptop, which is long for 10,000 orders.

Step 2 · Install hyperfine and time the script

A single run with a stopwatch is noisy: the first run reads files from disk, other programs compete for the CPU, and laptops change clock speed. hyperfine runs the command repeatedly and reports the mean, the standard deviation and the fastest and slowest run.

On Ubuntu, install the release package from the project's GitHub page. dpkg --print-architecture picks the right file for your machine (amd64 or arm64):

Bash
sudo apt update
sudo apt install -y curl
ARCH="$(dpkg --print-architecture)"
curl -fsSLO "https://github.com/sharkdp/hyperfine/releases/download/v2.0.0/hyperfine_2.0.0_${ARCH}.deb"
sudo dpkg -i "hyperfine_2.0.0_${ARCH}.deb"
hyperfine --version

A package installed with dpkg -i gets no updates from apt upgrade. To upgrade later, download the newer .deb from the releases page and run sudo dpkg -i on it again. On macOS, run brew install hyperfine and check that hyperfine --version shows 2.0 or later.

Now time the report. --warmup 1 runs it once without recording, so the file cache is warm. --runs 5 keeps the wait short; with no --runs, hyperfine picks the count itself, with a minimum of ten:

Bash
hyperfine --warmup 1 --runs 5 'python report.py'

hyperfine 2.0 runs the command directly, without a shell, so python is found on your PATH (the active virtual environment). If you need pipes or && inside a benchmarked command, add -S to run it through sh. hyperfine throws the script's own output away, so you only see the timings.

Check it worked

hyperfine prints a Time (mean ± σ) line for python report.py, something like 1.1 s ± 0.02 s, then the range of the fastest and slowest of the 5 runs. hyperfine 2.0 also shows peak memory by default. Write the mean down: it is the number you will beat. If σ is more than a few percent of the mean, close other heavy programs and run it again.

Step 3 · Find the slow function with cProfile

cProfile records every Python function call: how many times it ran, the time spent inside it (tottime) and the time spent inside it plus everything it called (cumtime). Save the results to a file, then print the top entries sorted by cumulative time:

Bash
python -m cProfile -o report.prof report.py
python -c "import pstats; pstats.Stats('report.prof').sort_stats('cumulative').print_stats(8)"

Read the table from the top. Cumulative sorting puts the entry points first, because main includes everything below it, so builtins.exec (how cProfile starts the script), <module>, main and total_by_country lead with almost the whole run each. The question is where the cumulative time stops being passed down. Something like this:

Text
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.312    1.312 {built-in method builtins.exec}
        1    0.000    0.000    1.312    1.312 report.py:1(<module>)
        1    0.000    0.000    1.312    1.312 report.py:35(main)
        1    0.004    0.000    1.268    1.268 report.py:22(total_by_country)
    10000    1.264    0.000    1.264    0.000 report.py:15(find_customer)
        1    0.009    0.000    0.043    0.043 report.py:7(make_data)

Your numbers will differ. The pattern will not: find_customer has a tottime almost equal to its cumtime, so the time is spent in its own code, not in anything it calls. It ran 10,000 times, once per order, and each call walks the customer list from the start until it finds a match. That is on average 2,500 dictionary lookups per order, or 25 million in total.

For a quick look without the extra file, python -m cProfile -s cumulative report.py prints the same table straight after the script's output. Sort by tottime instead (sort_stats('tottime')) when you want the functions that burn time themselves to rise to the top.

Check it worked

The table lists find_customer with 10000 in the ncalls column, and its tottime is most of the run. The script's country table appears above the profile output, so the profiler did not change what the program does. The profiled run is a little slower than the hyperfine mean: cProfile adds a small cost to every function call, which is why you time with hyperfine and profile with a profiler, never the other way round.

Step 4 · Record a flame graph with py-spy

cProfile hooks into every call, which slows the program, and gives you a table. py-spy samples from outside the process instead, so it barely slows the program, and it draws a graph: it reads the stack of the running Python process many times a second and counts how often each stack appears. Run the script under it and write the result as an SVG flame graph:

Bash
py-spy record -o profile.svg -- python report.py
ls -l profile.svg
grep -c "find_customer" profile.svg

Everything after -- is the command py-spy starts and watches. When the script ends, py-spy prints a short line about the samples it took and writes the file.

Permissions depend on your system. On Linux, py-spy may watch a program it started itself as an ordinary user. Attaching to a process that is already running, with py-spy record --pid 12345, usually needs sudo. On macOS, py-spy always needs sudo. Inside a Docker container, the py-spy documentation says to start the container with --cap-add SYS_PTRACE if you see a permission error.

Python 3.15 also ships its own sampling profiler. python -m profiling.sampling run --flamegraph report.py gives a similar picture without installing anything. py-spy works with older Python versions too, which is why it is the one used here.

Check it worked

profile.svg exists and is not empty. grep -c prints a number above 0, so the graph contains find_customer. Open the file in a web browser (on a server, copy it to your laptop with scp first). You see coloured bars, and hovering over one shows its function name and its share of the samples.

Step 5 · Read the flame graph

A flame graph is easy to misread, so learn the two directions before you trust it.

A flame graph of report.py. The full-width root bar for the module sits at the bottom with main above it. Above main, sorted by name, sit a very narrow format_report bar, a narrow make_data bar and a wide total_by_country bar. On top of total_by_country sits find_customer, about 86 percent of the width, with nothing above it. Labels explain that width is share of samples and height is call depth.
Width tells you where the time goes. Height only tells you who called whom.
  • Width is time. Each bar's width is the share of samples in which that function was on the stack. A bar that covers 86% of the width was running, or waiting on something it called, for about 86% of the run.
  • Height is call depth. A bar sits on top of the function that called it. A tall, thin tower is a deep chain of calls that takes almost no time. Height alone never means slow.
  • The exposed top edge is self time. Where nothing sits on a bar, that function was doing its own work. A wide bar with nothing on top is the place to look first.
  • Left to right is not time order. Identical stacks are merged into one bar, and the bars on each level are usually sorted by name. A bar on the left did not run first.

The root sits at one edge: some tools draw it at the bottom, as in the diagram, and some at the top. Either way, start at the bar that spans the full width and read away from it.

In your own profile.svg, find the wide bar with nothing on top. Click it to zoom in; click the root bar to zoom out again. Use the Search control in the top corner of the graph to highlight every bar whose name matches, with the matching share shown along the bottom.

Check it worked

Without looking back at the cProfile table, answer three questions from your graph: which function has the widest bar with nothing on top of it, roughly what share of the width it covers, and which function called it. You should get find_customer, most of the width, and total_by_country. If the widest bars are make_data or <module> and the run took only a few hundredths of a second, you are looking at a profile of a different script.

Step 6 · Fix the hot function

The problem is a linear search inside a loop: for every order, the code scans up to 5,000 customers. The work grows with orders times customers, so doubling both makes the script four times slower. The fix is to look each customer up by ID in a dictionary, which takes about the same time however many customers there are. Build the dictionary once, before the loop.

Keep report.py as it is so you can compare the two, and put the fixed version in a new file that reuses the unchanged functions:

Bash
cat > report_fast.py <<'PY'
from collections import defaultdict

from report import format_report, make_data


def total_by_country(customers, orders):
    by_id = {customer["id"]: customer for customer in customers}
    totals = defaultdict(int)
    for customer_id, amount_cents in orders:
        totals[by_id[customer_id]["country"]] += amount_cents
    return totals


def main():
    customers, orders = make_data()
    print(format_report(total_by_country(customers, orders)))


if __name__ == "__main__":
    main()
PY
python report_fast.py

A fast answer that is wrong is worse than a slow one, so compare the outputs line by line before you look at speed:

Bash
diff <(python report.py) <(python report_fast.py) && echo "same output"

In your own projects, a test suite does this job. Run it after every performance change.

Check it worked

python report_fast.py prints the same eight lines as before, and returns almost at once. diff prints nothing and the command ends with same output. If diff shows lines, the two versions disagree: check that both files call make_data() with no arguments.

Step 7 · Prove the speed-up with hyperfine

Benchmark both versions in one command. hyperfine runs them in turn, prints each one's timings and then compares them, naming the faster command and how many times faster it is. --export-json saves the results so you can quote exact numbers later:

Bash
hyperfine --warmup 1 --runs 5 --export-json compare.json 'python report.py' 'python report_fast.py'

Read the means from the JSON file with a few lines of Python. hyperfine 2.0 changed the file layout: the mean is under summary.time_wall_clock.mean, in seconds, where 1.x versions had a plain mean key:

Bash
python - <<'PY'
import json

with open("compare.json") as f:
    results = json.load(f)["results"]
slow, fast = (result["summary"]["time_wall_clock"]["mean"] for result in results)
print(f"slow {slow:.3f} s, fast {fast:.3f} s, {slow / fast:.0f}x faster")
PY

Most of what remains in the fast version is starting Python and generating the test data. If you profile report_fast.py with py-spy now, find_customer has gone and the time is spread across make_data and interpreter start-up. That is the signal to stop: there is no single wide bar left to fix.

Check it worked

hyperfine's comparison at the end names python report_fast.py as the faster command, many times faster than python report.py. The Python snippet prints a line such as slow 1.150 s, fast 0.045 s, 26x faster. Your exact ratio depends on your machine, but it should be well above 5. Put the before and after means in your commit message or pull request, so reviewers see the evidence rather than a claim.

Step 8 · Do the same in Node.js

The same loop works for JavaScript. This tutorial has no Node.js version of the report, so try it on one of your own Node scripts that takes a noticeable time to run. Node.js has a built-in sampling profiler: start the script with --cpu-prof and Node writes a .cpuprofile file in the current folder when the process exits.

Bash
node --cpu-prof your-script.js
ls *.cpuprofile

Open Chrome DevTools, go to the Performance panel and load the file. The flame chart there is ordered by time, unlike the merged flame graph above, but width still means time and depth still means calls. For timing, hyperfine works the same way: hyperfine --warmup 1 'node your-script.js', and after a fix, pass the old and new versions as two commands to compare them. To step through Node code line by line rather than measure it, see debug a Node.js app with the inspector.

Check it worked

After node --cpu-prof finishes, ls *.cpuprofile lists one file whose name starts with CPU. and contains the date and process ID. Loading it in the Performance panel shows bars named after the functions in your-script.js.

Step 9 · Clean up

Leave the virtual environment and remove the demo folder. This also removes the downloaded .deb, the profiles and both scripts:

Bash
deactivate
cd ~
rm -rf ~/profile-demo

If you do not want to keep hyperfine, remove its package:

Bash
sudo dpkg -r hyperfine

Check it worked

ls ~/profile-demo reports that there is no such file or directory. After removing the package, command -v hyperfine prints nothing.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.