Skip to content
Linux system performance · Chapter 7 of 21 Day 5: CPU II – profiling with perf and flame graphs

Day 5: CPU II – profiling with perf and flame graphs

Goal: use perf to find out where a program spends its CPU time, make call chains fully visible, create and read flame graphs, interpret hardware counters and examine the time in which a program is not computing · Duration: about 3.5 hours · Prerequisite: Day 0–4

Where we start

perf works with sudo, the hardware counters are available (Day 0, Drill 6), FlameGraph is in ~/FlameGraph, and a C compiler is installed. Three short checks:

Does perf count cycles?

# on perf1
sudo perf stat -e cycles -- true
  • perf stat -e cycles counts the cycles of the command after --; true does nothing and exits at once.

Expected (your numbers will differ):

 Performance counter stats for 'true':

           1950640      cycles                                                                

       0.021510803 seconds time elapsed

       0.000000000 seconds user
       0.011954000 seconds sys

What matters is the line with cycles: a number in front of it, not <not supported>.

Is FlameGraph there?

# on perf1
ls ~/FlameGraph/flamegraph.pl

Expected:

/home/ubuntu/FlameGraph/flamegraph.pl

Is gcc there?

# on perf1
gcc --version

Expected (excerpt – the first line):

gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0

If gcc is missing, install it with sudo apt-get install -y gcc (on perf1 it came with fio on Day 0).

Introduction

So far you have found out which process needs the CPU. Today you go one level deeper: Which function in that process? Is it your own code, a library, the kernel? The answer comes from a profiler. It looks many times per second at what is running on each CPU right now and keeps count. In the end you know in which functions the time gets stuck – and above all, by which path the program got there.

The standard profiler on Linux is perf. It is part of the kernel project and can do much more: read hardware counters, record tracepoints, follow system calls. Today you use it as a profiler and make the results visible with flame graphs – a visualization invented by Brendan Gregg that is now part of almost every profiling tool.

Along the way you will hit the three hurdles where profiling most often fails in practice: missing symbols, broken call chains, and programs that run in a language with its own interpreter. You learn the solution for all three.

Today you learn:

  • to measure instructions, cycles and IPC with perf stat – and why high IPC does not mean “good”,
  • to collect and evaluate samples including call chains with perf record and perf report,
  • why call chains break and how frame pointers, debug symbols and DWARF help,
  • to create and read flame graphs,
  • to profile Python programs with perf,
  • to see what a program is waiting for with offcputime – the off-CPU analysis.

Background

The picture for today: the photographer in the workshop

Picture a program as a workshop where people work on jobs. You want to know what most of the time goes into. So you hire a photographer who takes a photo 99 times per second.

  • Every photo is a sample. Whoever stands at the lathe on 90 % of the photos spends about 90 % of their time there.
  • The job ticket is the call chain. The photo shows not only who is working, but also who gave them the job – and who gave it to that person.
  • Name tags are symbols. Without tags the caption only says “station 0x194660” – an address instead of a name.
  • Frame pointers are routing slips on the door: Everyone who comes in sticks a note “coming from …” on it. The photographer reads the chain in seconds. Whoever sticks no note breaks the chain.
  • DWARF is the floor plan of the workshop: With it the path can be reconstructed afterwards even without notes – but the photographer has to capture a large section every time.
  • The flame graph is the stack of photos, sorted by job: The higher the stack, the more time went into it.
  • Off-CPU: The photographer only photographs whoever is working. Whoever waits at the parts counter is never in a picture. For that you need a time clock that measures how long someone was away.
  • IPC is the working pace: Someone can work very fast – on something completely unnecessary.

The terms

Term Meaning in the picture
Sample snapshot: which instruction was running on the CPU photo
Call chain (stack trace) chain of functions that led to the current one job ticket
Symbol name for an address in the program name tag
Frame pointer register with a pointer to the caller’s frame routing slip on the door
DWARF debug information that describes the layout of each frame floor plan
Flame graph all call chains as stacks, width = share sorted stack of photos
Off-CPU time time in which a thread does not compute but waits time clock
IPC instructions per cycle working pace

Remember: A profiler shows where work is computed. Where it waits, it does not show – that is what off-CPU analysis is for.

How a profiler works

perf record sets up a timer or a hardware counter so that it triggers an interrupt at fixed intervals – for example 99 times per second and CPU. On every interrupt the kernel notes which instruction was just executing (the instruction address) and, if requested, the call chain (stack trace): which function called the current one, which called that one, and so on down to main and below. After the run, perf report translates the addresses into function names and counts how often each function was hit.

Why 99 and not 100? So that the sampling does not accidentally run in lockstep with something that itself happens 100 times per second – otherwise you would always see the same moment.

Profiling is a sample. A function that shows up in 1 % of the samples used about 1 % of the CPU time. With few samples this is imprecise; a one-second run with 99 samples per CPU only shows the big chunks. For troubleshooting that is almost always enough: you are usually looking for one function that eats 30, 50 or 90 % of the time.

Symbols and call chains

To turn an address into a function name, perf needs the symbol table of the program or library. Many system libraries are shipped without full symbols to save space (stripped); the symbols live in separate debug packages.

For the call chain, perf has to walk backwards through the stack from the current instruction (stack walking). There are two ways:

  • Frame pointers. On entry every function puts a pointer to its caller’s frame into a fixed register (rbp on x86-64). The profiler can walk this chain in nanoseconds. For a long time, however, compilers left this pointer out (-fomit-frame-pointer, the default with -O2) to have one more register for computation. Then the chain breaks. Since 24.04, Ubuntu builds its packages with frame pointers again – precisely because of profiling. For your own programs you turn them on with -fno-omit-frame-pointer.
  • DWARF. The debug information of a program (format DWARF) describes how each frame is laid out. perf record --call-graph dwarf copies a piece of the stack with every sample and evaluates it later using this description. That works without frame pointers too, but costs much more space and time.

Flame graphs

A list of functions with percentages is hard to read when there are hundreds of different call chains. A flame graph shows all of them at once:

  • Every rectangle is a function. A function above another one was called by it. The program start is at the bottom, the function that was computing at the top.
  • The width of a rectangle is the share of samples in which this function was on the stack. Wide = a lot of time.
  • The x-axis is not a time axis. The rectangles are sorted alphabetically so that identical calls merge.
  • In the default setting the colors have no meaning; they only make the rectangles distinguishable.

You read a flame graph from the top: wide “plateaus” are functions that compute a lot themselves. Then you go down to see who called them.

IPC – instructions per cycle

Hardware counters show how the CPU works. The most important metric is IPC: executed instructions divided by cycles. A modern CPU can execute several instructions per cycle.

  • IPC below 1 usually means: the CPU waits a lot – for memory, for mispredicted branches. A case for optimizing data structures and memory access.
  • IPC above 1 means: the CPU is working smoothly.

But careful: high IPC only means that the CPU works efficiently – not that it does anything useful. Drill 2 shows a program that does unnecessary work with high IPC.

On-CPU and off-CPU

A profiler only sees what runs on the CPU. A program that is slow because it waits – for the disk, the network, a lock – hardly shows up in the profile. For this time there is off-CPU analysis: instead of taking samples, an eBPF program records every moment a thread gives up the CPU and measures how long it was away – with the call chain at which it went to sleep. On-CPU and off-CPU together make up the whole run time.

Drill 1: A program with a hidden problem

Where you are: on perf1, in the directory ~/tag05.

What you have afterwards: a small C program in two variants – with and without frame pointers.

Step 1 – a working directory.

# on perf1
mkdir -p ~/tag05
# on perf1
cd ~/tag05

Step 2 – create the program.

# on perf1
nano zaehler.c

Content (nano as on Day 0: Ctrl+O and Enter saves, Ctrl+X exits):

zaehler.c new file
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* Ersetzt jedes Zeichen c in text durch '_' und zählt die Ersetzungen. */
static long ersetze(char *text, char c)
{
    long n = 0;
    for (size_t i = 0; i < strlen(text); i++) {   /* strlen in jeder Runde! */
        if (text[i] == c) {
            text[i] = '_';
            n++;
        }
    }
    return n;
}

/* Baut einen Text aus laenge zufälligen Kleinbuchstaben. */
static char *baue_text(size_t laenge)
{
    char *t = malloc(laenge + 1);
    for (size_t i = 0; i < laenge; i++)
        t[i] = (char)('a' + rand() % 26);
    t[laenge] = '\0';
    return t;
}

int main(void)
{
    long summe = 0;
    for (int runde = 0; runde < 200; runde++) {
        char *text = baue_text(20000);
        summe += ersetze(text, 'e');
        free(text);
    }
    printf("ersetzt: %ld\n", summe);
    return 0;
}

The program builds a text of 20,000 random letters 200 times and replaces every e in it with an underscore. The important lines:

  • ersetze (“replace”) runs over the text with i and compares each character with c. The loop condition i < strlen(text) calls strlen on every iteration – a function that walks the whole text up to the terminating null character to count its length. With 20,000 characters that is 20,000 calls that each read up to 20,000 characters. The comment gives it away; in real life it is missing.
  • Because ersetze writes into the text (text[i] = '_'), the compiler may not simply move the strlen call in front of the loop – it cannot prove that the length does not change.
  • baue_text (“build text”) reserves memory with malloc and fills it with rand() % 26 random letters.

Step 3 – compile without frame pointers.

# on perf1
gcc -O2 -g -o zaehler zaehler.c
  • gcc is the C compiler. -O2 turns on the usual optimizations, as for real programs.
  • -g puts debug information (DWARF) into the program so that perf finds function names and lines.
  • -o zaehler sets the name of the executable (zaehler = “counter”).

Expected: no output – gcc only reports errors.

Step 4 – compile with frame pointers.

# on perf1
gcc -O2 -g -fno-omit-frame-pointer -o zaehler-fp zaehler.c
  • -fno-omit-frame-pointer: frame pointers are kept – every function sticks its routing slip.

Step 5 – the run time.

# on perf1
time ./zaehler

Expected:

ersetzt: 154090

real    0m1.387s
user    0m1.384s
sys 0m0.003s

Just under one and a half seconds, almost all in program code (user). For 200 × 20,000 characters that is suspiciously long – but why?

Remember: For profiling always compile with -g and, where possible, with -fno-omit-frame-pointer – otherwise names or chains will be missing later.

Save your progress? Sign up for free

Drill 2: perf stat – what the CPU does

Where you are: on perf1, in ~/tag05.

What you have afterwards: cycles, instructions and IPC of the program – and a first warning that high IPC can be deceptive.

Step 1 – hardware counters of a run.

# on perf1
sudo perf stat -e task-clock,cycles,instructions,cache-misses,branch-misses ./zaehler
Event Meaning
task-clock CPU time used
cycles cycles
instructions executed instructions
cache-misses accesses that were not served from the fastest cache
branch-misses mispredicted branches after which the CPU had to discard work

Expected:

ersetzt: 154090

 Performance counter stats for './zaehler':

           1640.11 msec task-clock                       #    0.998 CPUs utilized
        2831524180      cycles                           #    1.726 GHz
        6787953406      instructions                     #    2.40  insn per cycle
             96312      cache-misses
           4432102      branch-misses

       1.642791932 seconds time elapsed

       1.636629000 seconds user
       0.005864000 seconds sys

Almost 6.8 billion instructions for a few million characters. And the IPC of 2.40 is excellent: the CPU works without waiting, hardly any cache misses. Whoever only looks at IPC would say: nothing to gain here. The instruction count says the opposite – the program does a lot, just very efficiently. What it does, the profiler shows.

Remember: High IPC means “worked fast”, not “did useful work”. The instruction count reveals unnecessary work.

Save your progress? Sign up for free

Drill 3: perf record and perf report – and why the chain breaks

Where you are: on perf1, in ~/tag05.

What you have afterwards: three profiles of the same program – with unreadable addresses, with a broken chain and complete – and you know what is missing in each.

Step 1 – record the first profile.

# on perf1
sudo perf record -F 99 -g -o ohne-fp.data ./zaehler
  • perf record starts the program and takes samples.
  • -F 99 means 99 times per second, -g records the call chains (via frame pointers).
  • -o sets the file (the default would be perf.data).

Expected (the last lines):

[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.019 MB ohne-fp.data (153 samples) ]

153 samples in one and a half seconds.

Step 2 – evaluate.

# on perf1
sudo perf report -i ohne-fp.data --stdio --no-children
  • -i names the file, --stdio writes text instead of the interactive interface.
  • --no-children counts each function only where it computes itself (not additionally in all functions that called it).

Expected (excerpt – the beginning, blank lines left out):

# Total Lost Samples: 0
#
# Samples: 153  of event 'cycles:P'
# Event count (approx.): 2818062834
#
# Overhead  Command  Shared Object      Symbol
# ........  .......  .................  ......................
#
    24.29%  zaehler  libc.so.6          [.] 0x0000000000194660
            |
            ---0x71d36c394660
    17.13%  zaehler  libc.so.6          [.] 0x0000000000194640
            |
            ---0x71d36c394640
    13.88%  zaehler  libc.so.6          [.] 0x0000000000194654

Most of the time is in libc.so.6, the C standard library – but instead of function names there are only addresses, and the call chain consists of a single line. Two problems at once: no name tags, no job ticket.

Step 3 – symbols for the libc. The libc symbols are in the package libc6-dbg:

# on perf1
sudo apt-get install -y libc6-dbg

Step 4 – record the variant with frame pointers.

# on perf1
sudo perf record -F 99 -g -o mit-fp.data ./zaehler-fp
# on perf1
sudo perf report -i mit-fp.data --stdio --no-children

Expected (excerpt – from the header line of the table, blank lines left out):

# Overhead  Command     Shared Object      Symbol
# ........  ..........  .................  ...................................
#
    85.50%  zaehler-fp  libc.so.6          [.] __strlen_avx2_rtm
            |
            ---__strlen_avx2_rtm
               __libc_start_call_main
               __libc_start_main@@GLIBC_2.34
               _start
     7.24%  zaehler-fp  libc.so.6          [.] __random
            |
            ---__random
               rand
               main
               __libc_start_call_main
               __libc_start_main@@GLIBC_2.34
               _start
     1.45%  zaehler-fp  zaehler-fp         [.] main

Now the names are there: 85 % of the time in __strlen_avx2_rtm – that is strlen, in a version the libc selects for processors with AVX2 instructions. But the chain below has a gap: between strlen and __libc_start_call_main, main is missing. Who calls strlen? For the second hit (rand), however, main is there.

The reason: strlen is written in assembler and does not set up a frame pointer itself – it sticks no routing slip. When the sample hits in the middle of strlen, the register still points to the frame of main – and the profiler jumps from there directly to its caller. The directly calling function drops out. This is a typical weakness of the frame-pointer method with small, hand-optimized functions.

Step 5 – DWARF. Now the variant without frame pointers, but with the floor plan:

# on perf1
sudo perf record -F 99 --call-graph dwarf -o dwarf.data ./zaehler
  • --call-graph dwarf replaces -g: the stack is evaluated using the DWARF information. DWARF does not need frame pointers.

Expected (last line):

[ perf record: Captured and wrote 1.235 MB dwarf.data (152 samples) ]
# on perf1
sudo perf report -i dwarf.data --stdio --no-children

Expected (excerpt – from the header line of the table, blank lines left out):

# Overhead  Command  Shared Object      Symbol
# ........  .......  .................  ...........................
#
    90.75%  zaehler  libc.so.6          [.] __strlen_avx2_rtm
            |
            ---__strlen_avx2_rtm
               ersetze (inlined)
               main
               __libc_start_call_main
               __libc_start_main_impl (inlined)
               _start
     5.26%  zaehler  libc.so.6          [.] __random
            |
            ---__random
               rand
               baue_text (inlined)
               main

Now the chain is complete: main → ersetze → strlen, with 91 % of the time. (inlined) means that the compiler built ersetze directly into main; DWARF knows that anyway. The price is in the perf record line: 1.2 MB for 152 samples, compared with 19 KB with the frame-pointer method – more than sixty times as much. For long measurements on a whole server that quickly becomes too much.

Remember: Frame pointers for everyday use (fast, small, already there for system packages on Ubuntu 24.04), DWARF when the chain has gaps, debug packages when names are missing.

If it doesn’t work

  • Error: Access to performance monitoring … is limited: you forgot sudo (Day 0, Drill 6).
  • Still only addresses in libc.so.6: libc6-dbg does not exactly match the installed libc, for example after an update without restarting the packages. apt-cache policy libc6 libc6-dbg shows the versions; they must be the same.
  • perf report opens a full-screen interface: you forgot --stdio. Quit with q.

Save your progress? Sign up for free

Drill 4: The flame graph

Where you are: on perf1, in ~/tag05.

What you have afterwards: a flame graph as an SVG file that you can open in the browser.

The recording becomes a picture in three steps: print the samples as text, fold identical chains, draw.

Step 1 – every sample as text.

# on perf1
sudo perf script -i dwarf.data > dwarf.perf
  • perf script prints every single sample with its call chain as text.
  • > writes this output to the file dwarf.perf.

A look at the first sample:

# on perf1
head -8 dwarf.perf

Expected:

zaehler  176085 185276.753997:    6934074 cycles:P:
        7241a6b94654 __strlen_avx2_rtm+0xd4 (/usr/lib/x86_64-linux-gnu/libc.so.6)
        65505afb8169 ersetze+0x89 (inlined)
        65505afb8169 main+0x89 (/home/ubuntu/tag05/zaehler)
        7241a6a2a1c9 __libc_start_call_main+0x79 (/usr/lib/x86_64-linux-gnu/libc.so.6)
        7241a6a2a28a __libc_start_main_impl+0x8a (inlined)
        65505afb81d4 _start+0x24 (/home/ubuntu/tag05/zaehler)

Every sample starts with the program name, process ID, timestamp and the weight (here the number of cycles since the last sample). Below it the chain, with the computing function on top.

Step 2 – fold.

# on perf1
~/FlameGraph/stackcollapse-perf.pl dwarf.perf > dwarf.folded
  • stackcollapse-perf.pl from the FlameGraph project folds the output: every distinct call chain becomes one line, the functions separated by semicolons, followed by its weight.

The three heaviest chains:

# on perf1
sort -t" " -k2 -n -r dwarf.folded | head -3
  • sort -t" " -k2 -n -r sorts by the second space-separated field (the weight), numerically (-n) and in descending order (-r); head -3 keeps the first three lines.

Expected:

zaehler;_start;__libc_start_main_impl;__libc_start_call_main;main;ersetze;__strlen_avx2_rtm 2554444004
zaehler;_start;__libc_start_main_impl;__libc_start_call_main;main;baue_text;rand;__random 147926948
zaehler;_start;__libc_start_main_impl;__libc_start_call_main;main;ersetze 40693261

After folding only seven distinct chains remain; the top one combines almost everything with 2.55 billion cycles.

Step 3 – create the picture.

# on perf1
~/FlameGraph/flamegraph.pl --title "zaehler (perf, DWARF)" --width 1000 dwarf.folded > zaehler.svg
  • --title sets the heading, --width the width in pixels. The result is an SVG file.

Step 4 – fetch it to your computer. In the browser you can hover over the rectangles to see names and percentages, and click into them to zoom:

# on your computer
scp perf1:tag05/zaehler.svg .
  • scp copies files over SSH; perf1:tag05/zaehler.svg is the path relative to the home directory on perf1, . the current directory on your computer.
Flame graph of zaehler: almost the whole width belongs to __strlen_avx2_rtm above ersetze and main

Step 5 – read. From top to bottom:

  • The widest plateau at the top is __strlen_avx2_rtm – more than 90 % of the width. This is where the computing happens.
  • Below it ersetze, then main: that is the path there.
  • On the left a narrow tower with baue_text → rand → __random: generating the random texts, a good 5 %.
  • On the far right a thin, tall tower: kernel functions while loading the program. Unimportant.

The diagnosis: ersetze calls strlen far too often. The solution is obvious – determine the length once before the loop. More on that in the challenge.

Remember: perf script → stackcollapse-perf.pl → flamegraph.pl. Read the picture from the top: the widest plateau computes, below it stands who gave it the job.

Save your progress? Sign up for free

Drill 5: Off-CPU – what a program waits for

Where you are: in two terminals on perf1, in ~/tag05.

What you have afterwards: the call chains at which a writing process waits for the disk, as a list and as a flame graph.

A program that is slow because it waits looks harmless in the profile. Your example is dd writing with oflag=dsync: every single write waits until the data is safely on the disk – similar to the service from the diagnosis task of Day 2.

Step 1 – start the waiter.

# on perf1, terminal 1
dd if=/dev/zero of=/daten/sync.bin bs=4k count=20000 oflag=dsync status=none
  • bs=4k count=20000 writes 20,000 blocks of 4 KiB.
  • oflag=dsync demands confirmation after every block that it is on the disk.
  • status=none suppresses the final message.

dd runs for a while – 46 seconds in the lab. Let it run and do the next steps quickly.

Step 2 – the PID.

# on perf1, terminal 2
pgrep -x dd

Expected:

75696

You will see a different number. Use yours below instead of PID.

Step 3 – the time clock.

# on perf1, terminal 2
sudo offcputime-bpfcc -p PID 5
  • offcputime-bpfcc measures how long threads were not on the CPU, grouped by the call chain at which they gave up the CPU.
  • -p PID limits it to the dd process, 5 measures for five seconds.

Expected (excerpt – the largest block, at the very bottom of the output):

    finish_task_switch.isra.0
    schedule
    jbd2_log_wait_commit
    jbd2_complete_transaction
    ext4_fc_commit
    ext4_sync_file
    vfs_fsync_range
    ext4_buffered_write_iter
    ext4_file_write_iter
    vfs_write
    ksys_write
    __x64_sys_write
    x64_sys_call
    do_syscall_64
    entry_SYSCALL_64_after_hwframe
    __GI___write
    [unknown]
    __libc_start_call_main
    __libc_start_main_impl
    [unknown]
    -                dd (75696)
        3126176

Unlike with perf report, the function in which the thread slept is at the top here and the program start at the bottom. Read from the bottom: dd calls write, ext4 writes, has to synchronize because of dsync (ext4_sync_file) and waits in jbd2_log_wait_commit for the journal to be on disk. The number at the end is the total waiting time in microseconds: 3.13 seconds out of five. A second, smaller block directly above it (1.26 seconds) shows the waiting for the write-back of the data itself. [unknown] are frames in dd for which no symbols are installed.

Step 4 – folded for the flame graph. dd must still be running (every start of offcputime needs about 12 seconds to compile, hence the 46 seconds of dd):

# on perf1, terminal 2
sudo offcputime-bpfcc -f -p PID 5 > dd-offcpu.folded
  • -f prints the chains folded right away – suitable for flamegraph.pl.

Step 5 – stop dd and clean up. If dd is still running in terminal 1, stop it with Ctrl+C. Then:

# on perf1
rm -f /daten/sync.bin

Step 6 – the picture.

# on perf1
~/FlameGraph/flamegraph.pl --title "dd mit oflag=dsync: Off-CPU-Zeit" --countname us --colors io --width 1000 dd-offcpu.folded > dd-offcpu.svg
  • --countname us labels the values as microseconds.
  • --colors io selects a blue color palette that is commonly used for off-CPU graphs so they are not confused with on-CPU ones.
Off-CPU flame graph of dd: two towers, the wider one waits in jbd2_log_wait_commit, the narrower one in folio_wait_writeback

Two towers above ext4_sync_file: on the left, wide, the waiting for the journal; on the right the waiting for the write-back of the data pages (folio_wait_writeback, io_schedule). An on-CPU profile of the same program would have been almost empty.

Remember: Whoever waits is not in the photo. For waiting time you need the time clock: offcputime shows where a thread went to sleep and for how long.

If it doesn’t work

  • pgrep finds nothing or offcputime-bpfcc prints nothing: dd had already finished. Start it again in terminal 1 and measure faster – or increase count=20000.
  • The chains end in [unknown]: the debug symbols for dd are missing. For the kernel part that does not matter.

Save your progress? Sign up for free

Diagnosis task

A colleague has written a small Python script that calculates revenue from orders. It needs five seconds for 20,000 orders, and he wants to move it “to a bigger server”.

Setup.

# on perf1
cd ~/tag05
# on perf1
nano bericht.py

Content:

bericht.py new file
import random

def lade_kunden(anzahl):
    return [f"K{n:06d}" for n in range(anzahl)]

def lade_bestellungen(kunden, anzahl):
    return [(random.choice(kunden), random.randint(1, 500)) for _ in range(anzahl)]

def gesperrte_kunden(kunden):
    return [k for i, k in enumerate(kunden) if i % 7 == 0]

def summiere(bestellungen, gesperrt):
    summe = 0
    for kunde, betrag in bestellungen:
        if kunde not in gesperrt:
            summe += betrag
    return summe

def formatiere(summe):
    return f"Umsatz ohne gesperrte Kunden: {summe} EUR"

def main():
    random.seed(1)
    kunden = lade_kunden(50_000)
    bestellungen = lade_bestellungen(kunden, 20_000)
    gesperrt = gesperrte_kunden(kunden)
    print(formatiere(summiere(bestellungen, gesperrt)))

main()
# on perf1
time python3 bericht.py

Expected:

Umsatz ohne gesperrte Kunden: 4292861 EUR

real    0m5.061s
user    0m5.020s
sys 0m0.040s

Task (20 minutes): Use perf to find out in which Python function the time is spent – without reading the code. Hint: to perf, a Python program is at first just the interpreter python3. Since Python 3.12 there is the switch -X perf.

Solution path

Step 1 – first attempt, without the switch.

# on perf1
sudo perf record -F 99 -g -o py-ohne.data python3 bericht.py
# on perf1
sudo perf report -i py-ohne.data --stdio --no-children --sort symbol
  • --sort symbol groups by function name, no matter in which file.

Expected (excerpt – the first two functions):

    26.80%  [.] PyObject_RichCompareBool            -      -
                       0x608852
                       0x6b50d3
    26.49%  [.] __memcmp_avx2_movbe_rtm             -      -

The program spends its time on comparisons: PyObject_RichCompareBool compares two Python objects, memcmp compares memory areas (here: strings). But which line of Python code compares so much? The call chain only shows interpreter functions and addresses – photos without name tags.

Step 2 – second attempt, with -X perf.

# on perf1
sudo perf record -F 99 -g -o py-mit.data python3 -X perf bericht.py
  • python3 -X perf turns on the perf trampoline: for every Python function the interpreter creates a tiny piece of machine code and writes its address and name to a file /tmp/perf-PID.map, which perf reads automatically. That way Python functions appear as frames of their own.
# on perf1
sudo perf report -i py-mit.data --stdio --no-children --sort symbol -G
  • -G inverts the display of the chain: from the program start to the computing function – that is easier to read.

Expected (excerpt – the first function with its chain):

    29.72%  [.] __memcmp_avx2_movbe_rtm           -      -
            |
            ---__libc_start_main@@GLIBC_2.34
               __libc_start_call_main
               Py_BytesMain
               Py_RunMain
               _PyRun_AnyFileObject
               _PyRun_SimpleFileObject
               0x6b50d3
               0x608852
               PyEval_EvalCode
               py::<module>:/home/ubuntu/tag05/bericht.py
               _PyEval_EvalFrameDefault
               PyObject_Vectorcall
               py::main:/home/ubuntu/tag05/bericht.py
               _PyEval_EvalFrameDefault
               PyObject_Vectorcall
               py::summiere:/home/ubuntu/tag05/bericht.py
               _PyEval_EvalFrameDefault
               0x56098f
               PyObject_RichCompareBool
               __memcmp_avx2_movbe_rtm

Now the Python functions appear in the chain with the prefix py::: <module> → main → summiere (“sum up”) → comparison.

Step 3 – how large is the share of summiere? A flame graph shows it at a glance. The same three steps as in Drill 4:

# on perf1
sudo perf script -i py-mit.data > py.perf
# on perf1
~/FlameGraph/stackcollapse-perf.pl py.perf > py.folded
# on perf1
~/FlameGraph/flamegraph.pl --title "bericht.py (python3 -X perf)" --width 1000 --minwidth 5 py.folded > bericht.svg
  • --minwidth 5 leaves out rectangles that would be narrower than 5 pixels – otherwise the start of the interpreter creates a very tall, thin tower that stretches the picture.
Flame graph of bericht.py: py::summiere carries almost the whole width, above it comparison functions

py::summiere carries almost the whole width. In the lab, counting the folded chains gave 96.4 % of the samples with py::summiere in the chain – and above it only comparisons.

Step 4 – now read the code. if kunde not in gesperrt checks whether a customer (kunde) is in gesperrt (“blocked”). gesperrt is a list with more than 7,000 entries. in on a list compares with each entry in turn – with 20,000 orders up to 140 million string comparisons. Those are the RichCompare and memcmp plateaus in the flame graph.

Step 5 – the fix is one character. A set (set) finds an entry via a hash in constant time. Copy the script so that you can compare both versions:

# on perf1
cp bericht.py bericht-schnell.py
# on perf1
nano bericht-schnell.py

In gesperrte_kunden the square brackets become curly braces; the changed line is marked in green:

bericht-schnell.py changes in green
import random

def lade_kunden(anzahl):
    return [f"K{n:06d}" for n in range(anzahl)]

def lade_bestellungen(kunden, anzahl):
    return [(random.choice(kunden), random.randint(1, 500)) for _ in range(anzahl)]

def gesperrte_kunden(kunden):
    return {k for i, k in enumerate(kunden) if i % 7 == 0}

def summiere(bestellungen, gesperrt):
    summe = 0
    for kunde, betrag in bestellungen:
        if kunde not in gesperrt:
            summe += betrag
    return summe

def formatiere(summe):
    return f"Umsatz ohne gesperrte Kunden: {summe} EUR"

def main():
    random.seed(1)
    kunden = lade_kunden(50_000)
    bestellungen = lade_bestellungen(kunden, 20_000)
    gesperrt = gesperrte_kunden(kunden)
    print(formatiere(summiere(bestellungen, gesperrt)))

main()
  • Line 10: [k for …] builds a list, {k for …} a set with the same entries. Nothing else changes.

Step 6 – compare.

# on perf1
diff bericht.py bericht-schnell.py
  • diff shows the difference between the files.

Expected:

10c10
<     return [k for i, k in enumerate(kunden) if i % 7 == 0]
---
>     return {k for i, k in enumerate(kunden) if i % 7 == 0}

Step 7 – measure.

# on perf1
time python3 bericht-schnell.py

Expected:

Umsatz ohne gesperrte Kunden: 4292861 EUR

real    0m0.252s
user    0m0.219s
sys 0m0.033s

Same result, 0.25 instead of 5.06 seconds – twenty times faster. A bigger server might have brought 30 %.

If it doesn’t work

  • No py:: frames despite -X perf: Python is older than 3.12 (python3 --version). From 3.12 the switch works on Linux.
  • The flame graph shows no py::summiere: you printed py-ohne.data instead of py-mit.data.

Challenge

Fix the problem in zaehler.c: determine the length once before the loop. Then measure both versions with perf stat -r 3 and explain why the IPC of the fast version is lower.

Solution path:

# on perf1
cd ~/tag05
# on perf1
cp zaehler.c zaehler-schnell.c
# on perf1
nano zaehler-schnell.c

Change the copy so that it looks like this afterwards. The changed lines are marked in green:

zaehler-schnell.c changes in green
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* Ersetzt jedes Zeichen c in text durch '_' und zählt die Ersetzungen. */
static long ersetze(char *text, char c)
{
    long n = 0;
    size_t laenge = strlen(text);
    for (size_t i = 0; i < laenge; i++) {
        if (text[i] == c) {
            text[i] = '_';
            n++;
        }
    }
    return n;
}

/* Baut einen Text aus laenge zufälligen Kleinbuchstaben. */
static char *baue_text(size_t laenge)
{
    char *t = malloc(laenge + 1);
    for (size_t i = 0; i < laenge; i++)
        t[i] = (char)('a' + rand() % 26);
    t[laenge] = '\0';
    return t;
}

int main(void)
{
    long summe = 0;
    for (int runde = 0; runde < 200; runde++) {
        char *text = baue_text(20000);
        summe += ersetze(text, 'e');
        free(text);
    }
    printf("ersetzt: %ld\n", summe);
    return 0;
}
  • Line 9 is new: strlen runs once before the loop, the result is stored in laenge (“length”).
  • Line 10: the loop condition only compares with laenge. The comment /* strlen in jeder Runde! */ (“strlen in every round!”) goes away; it is no longer true.

Save, exit nano, then check:

# on perf1
grep -n -A1 "size_t laenge = strlen" zaehler-schnell.c
  • grep -n -A1 shows the line with size_t laenge = strlen with its line number (-n) and the one line after it (-A1).

Expected:

9:    size_t laenge = strlen(text);
10-    for (size_t i = 0; i < laenge; i++) {
# on perf1
gcc -O2 -g -o zaehler-schnell zaehler-schnell.c

Now measure both versions three times each:

# on perf1
sudo perf stat -r 3 -e task-clock,cycles,instructions ./zaehler-schnell
  • -r 3 runs the program three times and reports averages with their variation.

Expected (excerpt – the lines of the three counters and the elapsed time):

            190.31 msec task-clock                       #    0.993 CPUs utilized               ( +- 14.67% )
         297440307      cycles                           #    1.563 GHz                         ( +-  2.47% )
         314679456      instructions                     #    1.06  insn per cycle              ( +-  0.06% )
            0.1916 +- 0.0280 seconds time elapsed  ( +- 14.62% )
# on perf1
sudo perf stat -r 3 -e task-clock,cycles,instructions ./zaehler

Expected (excerpt):

           1534.27 msec task-clock                       #    0.999 CPUs utilized               ( +-  5.13% )
        2864707439      cycles                           #    1.867 GHz                         ( +-  1.52% )
        6787778180      instructions                     #    2.37  insn per cycle              ( +-  0.00% )
            1.5358 +- 0.0789 seconds time elapsed  ( +-  5.14% )

Eight times faster, with twenty-one times fewer instructions (0.31 instead of 6.79 billion). The IPC drops from 2.37 to 1.06 because what remains is harder for the CPU: the fast AVX2 loop in strlen, which checks 32 characters per instruction, is gone; what remains is rand() and the character-by-character loop with a hard-to-predict branch (if (text[i] == c)). IPC measures efficiency, not usefulness – the best optimization is often to leave work out.

Save your progress? Sign up for free

Checkpoint

# on perf1
ls ~/tag05/*.svg

Expected: bericht.svg, dd-offcpu.svg and zaehler.svg.

# on perf1
dpkg-query -W -f='${Status}\n' libc6-dbg

Expected: install ok installed.

# on perf1
ls /daten

Expected: only lost+found – sync.bin is deleted.

Test yourself

  1. perf report shows only addresses instead of names in libc.so.6. What is missing, and how do you fix it?
  2. The chain below a hot function has a gap. Which two ways out do you know, and what does the second one cost?
  3. How do you read a flame graph – from the top or from the bottom, and what does the width mean?
  4. A program has an IPC of 2.4. Does that mean there is nothing to optimize?
  5. A service is slow, but its CPU profile is almost empty. What do you measure next?
  6. How do you make Python functions visible to perf?

Answers:

  1. The symbols (name tags); install the debug package, for the libc libc6-dbg.
  2. Frame pointers (-fno-omit-frame-pointer) or DWARF (--call-graph dwarf); DWARF needs many times the space (in the lab 1.2 MB instead of 19 KB).
  3. From the top: the widest plateau computes itself, below it are the callers. Width = share of samples; the x-axis is not time.
  4. No – IPC measures efficiency. The instruction count can reveal unnecessary work (6.8 billion for a few million characters).
  5. With off-CPU analysis, for example offcputime-bpfcc – the service waits instead of computing.
  6. From Python 3.12 with python3 -X perf (or PYTHONPERFSUPPORT=1); the functions appear as py::….

Interview Note

“How do you find out why a process needs 100 % CPU?” – The answer that convinces: perf record -g at 99 Hz, evaluated as a flame graph, read from top to bottom. Whoever also names the pitfalls – missing symbols (debug packages), broken chains (frame pointers, DWARF as a way out) and interpreted languages (Python -X perf, similar agents for Java) – shows real experience. And whoever explains the difference between on-CPU and off-CPU analysis answers the follow-up question right away: “And if it is not computing but still slow?”

Enterprise Note

Profiling in production was tricky for a long time because symbols were missing and frame pointers were switched off. That has changed: Ubuntu and Fedora build their packages with frame pointers, and continuous profiling – an agent on every server that takes samples at a few hertz and collects them centrally – has become standard (for example with tools such as Parca or Pyroscope). The overhead is in the percent range and pays off, because after an incident you can see where the CPU went at the time. For your own software that means: build with -fno-omit-frame-pointer, keep debug information in separate packages and turn on the profiling interfaces for interpreted languages.

Summary

  • perf stat shows cycles, instructions and IPC. High IPC means efficient, not useful – the instruction count reveals unnecessary work.
  • perf record -F 99 -g takes samples with call chains, perf report --stdio --no-children evaluates them.
  • Names missing: debug packages (libc6-dbg). Chains broken: frame pointers (-fno-omit-frame-pointer) or DWARF (--call-graph dwarf, much larger).
  • Flame graph: perf script → stackcollapse-perf.pl → flamegraph.pl. Width = time, the top is where computing happens, the x-axis is not time.
  • Python from 3.12: python3 -X perf makes Python functions visible as py::….
  • Off-CPU: offcputime-bpfcc shows where threads wait; as a flame graph with -f.
  • Diagnoses today: strlen in the loop condition (8× faster after the fix), in on a list instead of a set (20× faster) – a bigger server finds neither.

Commands at a glance

Command What it does Parameters
gcc -O2 -g [-fno-omit-frame-pointer] -o PROG PROG.c compile a C program -O2 optimize, -g debug info, -o output
perf stat -e EREIGNISSE [-r 3] BEFEHL hardware counters of a run (EREIGNISSE = events, BEFEHL = command) -e events, -r repetitions
perf record -F 99 -g -o DATEI BEFEHL samples with call chains (frame pointers; DATEI = file) -F frequency, -g chains, -o file
perf record --call-graph dwarf … chains via DWARF –
perf report -i DATEI --stdio --no-children [-G] [--sort symbol] profile as text -G inverted chain
perf script -i DATEI > DATEI.perf every sample as text –
stackcollapse-perf.pl DATEI.perf > DATEI.folded fold samples –
sort -t" " -k2 -n -r DATEI.folded \| head -3 heaviest chains -k2 second field
flamegraph.pl --title … --width … [--minwidth 5] [--colors io] [--countname us] flame graph as SVG see Drill 4 and 5
offcputime-bpfcc [-f] -p PID SEKUNDEN off-CPU time by call chain (SEKUNDEN = seconds) -f folded, -p process
python3 -X perf SKRIPT make Python functions visible to perf (SKRIPT = script) from Python 3.12
apt-get install libc6-dbg debug symbols of the libc –
scp perf1:PFAD . fetch a file from the VM (PFAD = path) –

Contents

More