Skip to content
systemcoding.dev
Performance

Find Hot Functions With perf record and perf report

Sample a program with perf record, rank functions with perf report, and read the Overhead, Command and Symbol columns to find the code that burns your CPU time.

6 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Linux, GNU and Rust logos.

perf stat says a program is slow; perf record says which function to open. It interrupts the program many times a second, writes down the instruction address each time, and lets perf report group those addresses by function. This post works on a small C program with two functions that differ in cost, using perf 6.8 on Linux 6.8 with GCC 13, and follows counting cycles and cache misses with perf stat.

A program with an obvious suspect

The program parses a block of comma-separated numbers many times. One function is cheap, the other searches linearly for every field, which is the kind of mistake that hides in real code.

csv.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FIELDS 2000
#define ROUNDS 3000

static char line[FIELDS * 6];

static void build(void) {
    char *p = line;
    for (int i = 0; i < FIELDS; i++)
        p += sprintf(p, "%d,", i % 997);
}

static long parse_fast(const char *s) {
    long sum = 0;
    char *end;
    while (*s) {
        sum += strtol(s, &end, 10);
        s = *end == ',' ? end + 1 : end;
    }
    return sum;
}

static long parse_slow(const char *s) {
    long sum = 0;
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++) {
        if (i == 0 || s[i - 1] == ',')
            sum += atol(s + i);
        len = strlen(s);
    }
    return sum;
}

int main(void) {
    build();
    long a = 0, b = 0;
    for (int r = 0; r < ROUNDS; r++) {
        a += parse_fast(line);
        b += parse_slow(line);
    }
    printf("%ld %ld\n", a, b);
    return 0;
}

The slow version recomputes strlen on every loop iteration, so its cost grows with the square of the line length. Build with symbols, optimization and frame pointers:

Shell
gcc -O1 -g -fno-omit-frame-pointer csv.c -o csv

-O1 keeps GCC from hoisting the strlen call, which keeps the example honest; at -O2 the compiler may or may not move it, depending on its alias analysis, and that uncertainty is itself a reason to profile rather than reason from source.

Record

perf record runs the command and writes perf.data in the current directory:

Shell
perf record -F 999 ./csv
Text
2979081000 2979081000
[ perf record: Woken up 3 times to write data ]
[ perf record: Captured and wrote 0.642 MB perf.data (16213 samples) ]

-F 999 samples about 999 times per second of CPU time. Without -F, perf record defaults to 4000 Hz (the perf record documentation names -F and -c as the knobs). The sample count at the end tells you the statistical weight of the report: thousands of samples support a ranking, a handful do not. Do not run it on a program that finishes in a few milliseconds; lengthen the work, as ROUNDS does here.

Report

Shell
perf report --stdio
Text
  Overhead  Command  Shared Object      Symbol
  ........  .......  .................  ...................
    71.32%  csv      libc.so.6          [.] __strlen_avx2
    14.85%  csv      csv                [.] parse_slow
     6.40%  csv      libc.so.6          [.] ____strtol_l_internal
     3.12%  csv      libc.so.6          [.] atol
     2.01%  csv      csv                [.] parse_fast

The values will differ on your machine, but the shape tells the story. Each row is one symbol, sorted by the share of samples that landed in it. The columns mean:

  • Overhead is that share of all samples, so the column sums to about 100%.

  • Command is the process name, which matters when you record a system with many processes.

  • Shared Object is the binary or library the code lives in.

  • Symbol is the function, prefixed [.] for user space or [k] for the kernel.

The leader is __strlen_avx2, a libc function, not your code. The cause is in parse_slow calling strlen over and over, and the report alone shows the callee but not the caller. That is the point where you want call graphs, which perf record -g adds and recording call graphs explains. For now the lesson is that a hot libc symbol is a pointer to its caller.

Sort and filter

perf report has options that change what you see without recording again:

Shell
perf report --stdio --sort symbol --percent-limit 3
Text
  Overhead  Symbol
  ........  ...................
    71.32%  [.] __strlen_avx2
    14.85%  [.] parse_slow
     6.40%  [.] ____strtol_l_internal
     3.12%  [.] atol

--sort picks the columns that group the samples (comm, dso, symbol, sym and others), and --percent-limit hides rows below a threshold. Without --stdio, the same command opens an interactive TUI where you can press Enter on a symbol and choose to annotate it, which leads to perf annotate.

Fix and compare

Cache the length, rebuild and record again:

csv_fixed.cc
static long parse_slow(const char *s) {
    long sum = 0;
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++) {
        if (i == 0 || s[i - 1] == ',')
            sum += atol(s + i);
    }
    return sum;
}

Removing the len = strlen(s) line inside the loop leaves the result unchanged and removes the quadratic cost. After rebuilding, the report changes:

Text
  Overhead  Command  Shared Object      Symbol
  ........  .......  .................  ...................
    38.90%  csv      libc.so.6          [.] ____strtol_l_internal
    25.11%  csv      libc.so.6          [.] atol
    17.63%  csv      csv                [.] parse_slow
    12.40%  csv      csv                [.] parse_fast
     3.02%  csv      libc.so.6          [.] __strlen_avx2

strlen has dropped out of the lead, and the remaining time is spread across the actual parsing work. Percentages are shares of a smaller total now, so a share of 38% means something different from the 71% earlier. Compare absolute run time with perf stat, or use perf diff, rather than comparing percentages between runs.

Where this goes wrong

Three things trip beginners. The first is a stripped or optimized-away name: if perf report shows raw addresses such as 0x0000000000401136, the binary has no symbol table, and you need a build with symbols. The second is a skewed sample: one profile run of a program with several phases shows only the phases that ran. The third is trusting percentages for functions that are close together; with a few hundred samples, 6% and 7% are not distinguishable. And perf record samples CPU time, so a program that sleeps or waits on I/O under-represents that wait, which is a job for off-CPU analysis.

Choosing the sampling basis

By default perf record samples the cycles event, so each sample represents a slice of CPU time, and a function with twice the samples consumed about twice the cycles. You can change the basis with -e. Sampling cache-misses makes the report rank functions by how many cache misses they caused rather than by time, which finds the code responsible for memory stalls even if a different function absorbs the waiting time. Sampling branch-misses does the same for mispredictions. The syntax is the same as for counting:

Shell
perf record -e cache-misses -c 10000 ./csv
Text
2979081000 2979081000
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.081 MB perf.data (1204 samples) ]

Here -c 10000 asks for one sample per 10,000 events instead of a time-based rate. The count shown is an example. The -F and -c options are alternatives, and the manual page for perf record notes that you give one or the other. A count-based period is the better choice for rare events, where a time-based rate would collect nothing.

Reading a report with several processes

When you record more than one program, the Command and Shared Object columns do the work. Sort by comm,dso to see which process and which library cost the most before descending into symbols, which keeps a build tool run, with compilers and shells below it, from burying the one binary you care about. Use perf report --comm csv to restrict the report to a single command once you know which one it is.

Keep the recording and the binary together

A perf.data file stores addresses, not names. The names are looked up when you run perf report, using the binaries on disk at that moment. If you rebuild between recording and reporting, the addresses no longer match the code, and the report either fails or attributes samples to the wrong functions. Treat the pair as one artifact: either report straight after recording, or archive the exact binary beside the data. perf archive bundles the binaries a recording touched into a tarball, which lets you analyze the data on another machine.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.