The Complete Guide to Profiling on Linux With perf
Learn perf from first run to expert use: counting, sampling, call graphs, flame graphs, memory and scheduler analysis, tracing and a measurement workflow.

Most slow programs are slow for one of four reasons: they execute too many instructions, they wait for memory, they mispredict branches, or they wait for something that is not the CPU at all. Guessing which one is how people spend a week optimizing the wrong function. On Linux, one tool that ships with the kernel can tell the four apart in about ten minutes: perf. It counts what the processor and the kernel do, samples where the program was while it did it, traces events as they happen, and records everything to a file you can analyze again tomorrow. This guide is the map of that tool. It starts with a five-minute first measurement, builds up through counting, sampling, call graphs and flame graphs, moves on to memory, scheduler, kernel and tracing work, and finishes with the discipline that makes the numbers trustworthy. Every command here is for perf 6.8 on Linux 6.8 with GCC 13, and each section links to a post that goes deeper.
One running example carries the guide. It is a small ledger program that generates account events, applies them to a table, and computes a checksum. It has one phase that is slow because of memory, one that is slow because of arithmetic, and one that is cheap, so every tool in this guide has something real to find. The program is written, never run, for this guide, so the outputs shown are illustrations of the format and your numbers will differ. The ratios and the ranking are what you should expect to reproduce.
What perf actually is
perf is two things with one name. The first is a kernel subsystem, the performance events subsystem, reached through one system call, perf_event_open(2). A program asks the kernel to open an event, such as "count retired instructions for this process" or "sample the instruction pointer every 100,000 cycles", and gets back a file descriptor it can read counts from or map a ring buffer from. The second is the user-space tool, perf, built from the kernel source tree under tools/perf, that makes those requests, formats the results and records them to perf.data. When people say "perf", they mean the tool, and when they say "the PMU" they mean the hardware.
The PMU, the performance monitoring unit, is a block of registers in every core. A few of them are counters that the hardware increments on events: a cycle passing, an instruction retiring, a branch being mispredicted, a cache line being missed. The kernel programs which event each counter watches and can make a counter raise an interrupt when it overflows. That one mechanism supports both modes of perf:
Counting reads a counter at the end and reports the total. It is exact, adds almost no overhead, and gives numbers for the whole run. This is
perf stat.Sampling loads a counter with a negative value so it overflows after N events. Each overflow interrupts the program, and the handler records where it was, plus optionally the call stack. Do this thousands of times and the pile of samples becomes a statistical picture of where the events happened. This is
perf record.
Alongside hardware events, perf also exposes software events counted by the kernel itself, such as context switches and page faults, and tracepoints, which are static hooks the kernel developers placed in the scheduler, the block layer, the network stack and elsewhere. And through uprobes and kprobes it can create new tracepoints in running code. Everything arrives through the same ring buffer, in the same file format, readable by the same report and script commands.
That uniformity is the reason to learn this one tool well. It does what a counter-based profiler, a sampling profiler, a system call tracer, a scheduler tracer and a dynamic tracer do separately elsewhere, with one command line vocabulary. The cost is that it has a lot of options, and the rest of this guide is a route through them.
Getting ready: install, permissions and symbols
Three things decide whether the first run works: the package, the permission and the symbols.
On Ubuntu and Debian the package carries the kernel version in its name, so install the generic one plus the matching one for the running kernel:
sudo apt install linux-tools-generic linux-tools-$(uname -r)
perf --versionperf version 6.8.12Fedora and Arch ship it as perf. If your kernel is custom or newer than the packages, build perf from the kernel source tree so the tool and the kernel agree about events. A tool a few releases older than the kernel works for basics, and a tool much newer asks for features the kernel does not have.
Permission is the second gate. The sysctl kernel.perf_event_paranoid decides what an unprivileged user may measure, and the sysctl kernel.kptr_restrict decides whether kernel addresses can be turned into names. Read them before blaming perf:
cat /proc/sys/kernel/perf_event_paranoid
cat /proc/sys/kernel/kptr_restrict2
1At 2, you can profile your own user-space code. At 1, you can also see kernel samples for your own processes. At 0, you can measure whole CPUs. Debian and Ubuntu kernels add levels 3 and above that block unprivileged use entirely. For a development machine, setting the first to 1 and the second to 0 is common. For a shared server, give the perf binary the CAP_PERFMON capability and leave the sysctls alone. Preparing a Linux box for profiling lays out each level and the capability setup.
Symbols are the third gate, and the one that silently ruins the most profiles. A report is a list of addresses until perf can turn them into function names and lines. Build the program with -g for line information and, for the best call graphs, -fno-omit-frame-pointer, which keeps the frame pointer register as a frame pointer instead of a general register:
gcc -O2 -g -fno-omit-frame-pointer ledger.c -o ledgerKeep -O2, or whatever level you ship. A profile of an unoptimized build describes a different program. For binaries you ship stripped, split the debug information into a separate file and index it, as in shipping separate debug symbols with objcopy and debuginfod, so that you can still profile a release build after the fact.
The running example
Here is the program. It has three phases that stress three different parts of the machine:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define ACCOUNTS (1u << 20)
#define EVENTS 20000000u
struct account {
int64_t balance;
uint32_t flags;
uint32_t pad[13];
};
static struct account accounts[ACCOUNTS];
static uint32_t ids[EVENTS];
static int32_t amounts[EVENTS];
static uint32_t next_rand(uint32_t *s) {
*s = *s * 1664525u + 1013904223u;
return *s;
}
static void generate(void) {
uint32_t s = 1;
for (uint32_t i = 0; i < EVENTS; i++) {
ids[i] = next_rand(&s) & (ACCOUNTS - 1);
amounts[i] = (int32_t)(next_rand(&s) % 2001) - 1000;
}
}
static void apply(void) {
for (uint32_t i = 0; i < EVENTS; i++)
accounts[ids[i]].balance += amounts[i];
}
static uint64_t checksum(void) {
uint64_t h = 1469598103934665603ull;
for (uint32_t r = 0; r < 40; r++)
for (uint32_t i = 0; i < ACCOUNTS; i++) {
h ^= (uint64_t)accounts[i].balance;
h *= 1099511628211ull;
}
return h;
}
int main(void) {
generate();
apply();
uint64_t h = checksum();
printf("events=%u accounts=%u checksum=%016llx\n",
EVENTS, ACCOUNTS, (unsigned long long)h);
return 0;
}The struct account is 64 bytes, exactly one cache line. apply updates the account chosen by ids[i], and because the ids are pseudo-random, each update touches a random line out of 64 MiB of table. That is memory bound by construction. checksum walks the table in order with a multiply that depends on the previous one, so it is compute bound by a dependency chain, not by memory. generate is sequential and cheap. The checksum value depends on the generator and the arithmetic, so the output block below shows a plausible value, and yours would match only if you ran the same code.
events=20000000 accounts=1048576 checksum=9f3a52c7d1e84b06Your first measurement: perf stat
Before looking for a function, find out what kind of slow this is. perf stat runs the command and prints counters when it exits:
perf stat ./ledgerevents=20000000 accounts=1048576 checksum=9f3a52c7d1e84b06
Performance counter stats for './ledger':
2,960.12 msec task-clock # 0.998 CPUs utilized
4 context-switches # 1.351 /sec
0 cpu-migrations # 0.000 /sec
103,402 page-faults # 34.932 K/sec
11,102,884,310 cycles # 3.751 GHz
6,312,445,120 instructions # 0.57 insn per cycle
990,512,004 branches # 334.616 M/sec
1,402,118 branch-misses # 0.14% of all branches
2.966410318 seconds time elapsedRead it as a doctor reads a chart. 0.998 CPUs utilized and a task-clock close to elapsed time say the process was running, not waiting, so CPU profiling is the right tool. The page-faults count is the kernel mapping the 224 MiB of static arrays on first touch. The branch miss rate is tiny, so branches are not the problem. The one number that stands out is 0.57 insn per cycle. A modern core can retire several instructions per cycle, and this one retired about half of one, so cycles passed in which nothing retired: the core was waiting, and on a program like this the likely thing it waits for is memory. Counting cycles, instructions and cache misses with perf stat explains how to read the other lines and when each ratio misleads.
Confirm the guess with the cache events:
perf stat -e cycles,instructions,cache-references,cache-misses ./ledger 2>&1 | tail -9 11,098,100,442 cycles
6,312,401,877 instructions # 0.57 insn per cycle
412,330,951 cache-references
198,402,116 cache-misses # 48.12% of all cache refs
2.961302115 seconds time elapsedNearly half of last-level cache references miss. That is the apply phase, 20 million updates to random lines of a table far larger than any cache. The counters say "memory bound" before any code has been opened. When the counters and your mental model disagree, trust the counters.
Two cautions belong here. First, one run is one sample: repeat with perf stat -r 5 to see the spread, because cycle counts move with frequency scaling and neighbors. Second, a request for more events than the processor has counters makes the kernel time-slice them, and the printed totals become scaled estimates. A percentage in brackets next to an event is the cue. How perf multiplexes counters and how to group events shows how to keep a ratio's numerator and denominator in one group so they are counted together.
Finding the function: perf record and perf report
Counting says what kind of problem; sampling says where. Record the run:
perf record -F 999 ./ledgerevents=20000000 accounts=1048576 checksum=9f3a52c7d1e84b06
[ perf record: Woken up 3 times to write data ]
[ perf record: Captured and wrote 0.820 MB perf.data (2958 samples) ]-F 999 asks for about 999 samples per second of CPU time; the odd number avoids lining up with periodic activity at round frequencies. With a program that runs three seconds, that is about three thousand samples, enough for a ranking of big items and not enough for fine differences. Read the file:
perf report --stdio --no-children Overhead Command Shared Object Symbol
........ ....... ............. ......
61.80% ledger ledger [.] apply
24.10% ledger ledger [.] checksum
10.20% ledger ledger [.] generate
3.90% ledger [kernel.kallsyms] [k] clear_page_ermsThe report ranks symbols by the share of samples. apply is the answer to "where does the time go", and the kernel row is the page-fault cost of first touch. The columns, the sort keys and the reasons a ranking can mislead are covered in finding hot functions with perf record and perf report. Two options change a report without re-recording: --sort picks the grouping keys (comm, dso, symbol, srcline) and --percent-limit hides the small rows.
A sample is a statistical observation, so a few thousand samples support a ranking of items that differ by a lot. A function at 61.80% against one at 24.10% is a safe call. Two functions at 6.1% and 5.9% are not distinguishable. The error shrinks with the square root of the sample count, which is why how sampling profilers work is worth reading before arguing about small differences, and why raising -F or lengthening the run is the cure for a ranking that wobbles between runs.
By default perf record samples the cycles event, so a sample means "this much CPU time passed". You can change the question by changing the event. Sampling cache-misses ranks functions by the misses they cause, which finds the code that costs memory bandwidth even when its neighbors absorb the waiting:
perf record -e cache-misses -c 100000 ./ledger
perf report --stdio --no-children --percent-limit 2 Overhead Command Shared Object Symbol
97.40% ledger ledger [.] apply
2.30% ledger ledger [.] generate-c 100000 asks for one sample per 100,000 events instead of a time-based rate, which suits rare events. Now the picture is consistent: apply is both the biggest consumer of time and nearly all of the cache misses. checksum, at 24% of the time, causes almost none, so its cost is something else. That something else is the multiply chain, and you can see it at instruction level.
Instruction level: perf annotate
A function is still a lot of code. perf annotate attaches the samples to individual instructions and, with -g in the build, to source lines:
perf annotate --stdio -s checksum Percent | Source code & Disassembly of checksum for cycles (713 samples)
-----------------------------------------------------------------------
: h ^= (uint64_t)accounts[i].balance;
21.40 : 401240: xor (%rdx),%rax
: h *= 1099511628211ull;
71.80 : 401243: imul %rcx,%rax
4.10 : 401247: add $0x40,%rdxMost of the time sits on the imul. Each iteration multiplies the result of the previous iteration, so the loop is limited by the multiplier's latency, not by memory or by instruction count. No amount of cache work will speed it up. Only a different structure, such as interleaving two independent hashes, can. That is a diagnosis you could not reach from the function-level report, and it follows from three things the report did not say: the instruction, its neighbors and the dependency in the source.
Two cautions apply to every annotation. The hot instruction is often the one after the slow one, because the interrupt is delivered after the processor retires something, an effect called skid, so read clusters of rows. And the percentages are relative to the function, so open the annotation only for a function worth the effort. Finding hot instructions with perf annotate works through both, and precise sampling modes such as cycles:pp reduce skid on hardware that supports them.
Who called it: call graphs
A report that says memcpy is hot invites the question "called from where?". Adding -g records the call stack with each sample:
perf record -F 999 -g ./ledger
perf report --stdio --no-children -G --percent-limit 5 | head -20 61.80% ledger ledger [.] apply
|
---apply
main
__libc_start_call_main
__libc_start_main_impl
_start-G inverts the graph so the hot function comes first and its callers follow. In this program the chain is trivial. In a real service it is where you learn that a hot hash function is being called from a logging path nobody expected.
The stacks only exist if the program leaves a trail perf can follow. There are three methods, and the choice is a trade between cost and requirements:
| Option | How it unwinds | Needs | Cost |
|---|---|---|---|
-g or --call-graph fp | Follows saved frame pointers | Code built with frame pointers | Lowest |
--call-graph dwarf | Copies stack bytes, unwinds later with DWARF CFI | Unwind tables, symbols | Large files, slow reports |
--call-graph lbr | Reads the hardware branch record | A supporting CPU | Low, depth limited |
GCC drops the frame pointer by default at -O1 and above on x86-64, so a plain -g recording of an optimized program often shows stacks one or two frames deep. That is the most common surprise in all of perf. The fixes are -fno-omit-frame-pointer at build time or --call-graph dwarf at record time, as explained in recording call graphs with perf record -g and --call-graph dwarf, and the comparison of the three methods and their failure modes is in frame pointer vs DWARF vs LBR call graphs.
Choose by what you can change. If you build the code, use frame pointers: they are cheap and reliable, and several distributions now build their whole system that way. If you cannot rebuild, use DWARF with a modest frequency such as 99 or 499 Hz, a stack dump size set with --call-graph dwarf,16384 if stacks are deep, and short recordings. If you have a supporting Intel part and shallow stacks suffice, LBR gives the lowest overhead.
Seeing the whole shape: flame graphs
A table of functions is precise and hard to hold in your head. A flame graph merges every sampled stack into one picture in which a box's width is the share of samples that passed through it. Brendan Gregg's FlameGraph scripts turn perf script output into an SVG in a pipe:
perf script | ./stackcollapse-perf.pl | ./flamegraph.pl > ledger.svgThe middle step folds each stack onto a single line with a count, and it is worth keeping the folded text, because it is small, diffable and reusable:
ledger;_start;__libc_start_main_impl;__libc_start_call_main;main;apply 1831
ledger;_start;__libc_start_main_impl;__libc_start_call_main;main;checksum 714
ledger;_start;__libc_start_main_impl;__libc_start_call_main;main;generate 303The counts are illustrative; the three lines mirror the report above. Open the SVG in a browser and the picture has a wide main base with apply, checksum and generate side by side above it, apply the widest. Reading rules are few and easy to get backwards: width is cost, height is only call depth, left-to-right order is alphabetical and means nothing, and colors are decoration. Look for wide boxes with nothing above them, the plateaus, because those are the functions that burn CPU themselves. How to read a flame graph teaches the reading with a worked example, and generating flame graphs from perf data covers the options.
A flame graph shows CPU time only. A thread that sleeps, blocks on a lock or waits for a disk is not on a CPU, so no sample lands on it and no box appears. A slow service whose flame graph looks healthy is usually a service that waits. Keep that in mind for the next sections.
When the CPU is not the problem: scheduler and off-CPU time
If task-clock is much smaller than time elapsed, the process spent the difference somewhere other than a CPU, and sampling cannot see it. The scheduler can. perf sched records the kernel's scheduling tracepoints, so every context switch and wake-up is captured:
perf sched record -- ./server_workload
perf sched latency --sort max Task | Runtime ms | Switches | Avg delay ms | Max delay ms |
worker:(8) | 9511.204 ms | 2410 | avg: 3.421 ms | max: 24.108 ms |
periodic:41250 | 61.882 ms | 300 | avg: 3.810 ms | max: 20.455 ms |This table is from a contended machine, not from ledger, which has nothing to wait for. The periodic task needed only 62 ms of CPU in total yet waited on average almost four milliseconds each time it became runnable. A CPU profile of it would show a few percent and say nothing about the delay. perf sched timehist breaks each wake-up into wait time, scheduling delay and run time, and perf sched map shows which task held which CPU over time. The remedies are the usual ones, fewer runnable threads, priorities, pinning, and the walkthrough with a workload that reproduces it is in finding scheduler delays and off-CPU time with perf sched.
When the waiting is for the kernel, not for a CPU, system calls are the next suspects. strace shows them at a cost, because it stops the process twice for every call. perf trace reads the same events from tracepoints and does not stop anything:
perf trace -s ./ledger 2>&1 | tail -10 ledger (41310), 214 events, 100.0%
syscall calls errors total min avg max stddev
(msec) (msec) (msec) (msec) (%)
--------------- -------- ------ -------- --------- --------- --------- ------
brk 4 0 0.021 0.003 0.005 0.009 18.12%
mmap 21 0 0.188 0.004 0.009 0.031 14.30%
openat 6 0 0.062 0.008 0.010 0.015 9.22%ledger makes almost no system calls, which is the answer: nothing to find there. For a service that does, the same table lists the slow and the failing calls, and --duration and --failure filter them on a live process. Using perf trace as a lower-overhead strace covers filters, summaries and what strace still does better.
Attaching to something already running
The commands above start the program themselves. A production process is already running, and restarting it destroys the evidence. perf top -p PID is a live, self-aging ranking, and perf record -p PID -- sleep 30 captures a bounded window without stopping the target:
perf top -p 18342
perf record -F 99 -g -p 18342 -- sleep 30Use a low frequency first, 99 Hz, because the cost is the interrupt per sample. Choose between the live view and a file on purpose: the live view answers "what is it doing right now" and the file answers "what did it do during these thirty seconds", and only the file can be attached to a ticket, diffed or turned into a flame graph. Profiling a running process with perf top and perf record -p covers threads, children and the rest.
Memory: where the stalls are
Back to ledger. The counters and the sampled cache-misses event said apply waits on memory. The next question is which data. A normal sample records the instruction pointer; perf mem also records the data address of each sampled load, which level of the memory hierarchy served it and how long it took:
perf mem record -t load ./ledger
perf mem report --stdio --sort mem Overhead Samples Memory access
78.60% 9102 RAM or RAM hit
13.20% 1530 LFB or LFB hit
5.10% 590 L3 or L3 hit
3.10% 360 L1 or L1 hitAlmost four fifths of the sampled loads were served by main memory. perf mem report can sort by data symbol and address, and perf script -F ip,sym,addr prints the addresses so you can see the access pattern directly. For apply the addresses jump all over a 64 MiB range, which is the pattern a prefetcher cannot follow. The fixes are about data: sort or bucket the events by account so updates to nearby accounts happen together, shrink the record so more fit in the cache, or process in blocks that fit. Finding memory access hot spots with perf mem shows a layout change that raises the useful bytes per cache line.
The memory facilities need hardware support (Intel PEBS load latency, AMD IBS, Arm SPE) and usually are missing in virtual machines. There is one more memory problem that only shows up with threads. Two threads that write different variables in the same 64-byte line force the line to bounce between their caches, and each core's cache keeps invalidating the other's. That is false sharing, and perf c2c finds it by counting the loads that hit a line modified in another core's cache:
perf c2c record ./threaded_ledger
perf c2c report --stdioThe report ranks cache lines by those events and shows which offsets within the line each thread touched. Different offsets from different threads means false sharing, fixed by aligning each hot per-thread value to its own line; the same offset from several threads means true sharing, which needs a different design. Detecting false sharing between threads with perf c2c walks through both outcomes.
Branches
The ledger program has almost no branch misses, but a program that tests data against a threshold does. The counter pair branches and branch-misses gives the rate, and a comparison of the same loop on sorted and shuffled input isolates the cause:
perf stat -e cycles,instructions,branches,branch-misses ./branchy shuffled
perf stat -e cycles,instructions,branches,branch-misses ./branchy sortedWhen the instruction counts are the same and the cycles differ by a large factor, the difference is prediction. Sampling on branch-misses with -c and annotating the function finds the branch. The remedies are to make the data predictable, to restructure so the branch becomes arithmetic, or to let the compiler use conditional moves. Measuring branch mispredictions with perf stat works through the experiment end to end.
One method for all of it: top-down analysis
IPC says the core was not busy; it does not say why. On Intel cores with the right counters, top-down analysis classifies every pipeline slot into one of four buckets, retiring, bad speculation, frontend bound and backend bound, summing to 100%:
perf stat -M TopdownL1 ./ledger tma_backend_bound % tma_slots 78.2
tma_bad_speculation % tma_slots 0.6
tma_frontend_bound % tma_slots 2.4
tma_retiring % tma_slots 18.8The values are illustrative; the shape is what a program like this produces. A dominant backend bound share sends you to the next level, -M TopdownL2, which splits it into memory bound and core bound, and a memory bound result sends you to perf mem. A dominant bad speculation share sends you to the branch counters, and frontend bound to instruction cache and code layout. The method's value is that it replaces a pile of counters with a decision procedure: expand only the largest non-retiring bucket. Running top-down analysis with perf stat is the hands-on guide, and top-down microarchitecture analysis explained gives the model behind the numbers. The facility is processor specific and generally unavailable in virtual machines.
Naming events: generic, vendor and raw
So far the events had friendly names. perf list shows three layers of them. Generic names such as cycles and cache-misses are aliases the kernel maps per architecture, so the same name can count slightly different things on two machines. Vendor names such as mem_load_retired.l3_miss come from tables shipped with perf for each processor model. When your processor is newer than your tool, you can program the hardware directly with a raw encoding, rNNNN for umask and event or the readable cpu/event=0xd1,umask=0x20/ form:
perf stat -e cpu/event=0xd1,umask=0x20,name=l3_miss/ ./ledgerperf stat -vv prints the attributes perf actually opened, which is the way to see what a generic name means on this machine. A wrong raw code counts something silently, so verify it against a program whose behavior you know. Using hardware event names and raw PMU events from perf list lists the modifiers, the hybrid CPU pitfalls and the verification steps.
Tracing: seeing every event, not a sample
Sampling answers "where did time go". It cannot answer "how often was this function called" or "what arguments did it get". For that you trace, and perf can plant a tracepoint in code that has none. A uprobe patches an instruction in a user binary with a breakpoint, and each hit becomes an event:
sudo perf probe -x ./ledger 'apply'
sudo perf record -e probe_ledger:apply ./ledger
sudo perf script -F traceWith debug information perf probe can also fetch named arguments and local variables and probe a function's return value, and with --filter at record time it keeps only the interesting hits. Each hit costs a trap, so probe moderate-rate functions. The static tracepoints that kernel developers placed in the scheduler, the block layer and the network stack are available the same way, -e sched:sched_switch or -e block:block_rq_issue. Adding dynamic tracepoints to user code with perf probe covers arguments, return probes, durations and cleanup, because probes stay in the kernel until you remove them.
When the question needs the exact path the code took, not a count, Intel Processor Trace records every branch with low overhead and a decoder reconstructs the instructions afterward:
perf record -e intel_pt//u ./ledger
perf script --itrace=cr -F time,event,sym --ns | headThe data volume is large and decoding is slow, so use address filters or snapshot mode. It is the tool for the one request out of a thousand that was slow, where a sampling profile has averaged the slow case away. Capturing instruction-level traces with Intel PT and perf shows the filters and the call-and-return timing technique.
The kernel is code too
When top shows high system time, a profile of your program is nearly empty because the time is in the kernel working for it. perf samples kernel code the same way, resolving addresses through /proc/kallsyms, and joins kernel and user stacks in one call graph:
sudo perf record -F 999 -g ./copyloop
sudo perf report --stdio --no-children --sort symbol | headRead such stacks bottom up, from the system call entry to the function that burns the time, and recognize the usual suspects: copy_user_enhanced_fast_string and clear_user are data movement across the user boundary, native_queued_spin_lock_slowpath is lock contention, handle_mm_fault is page faults, and the swapper command is the idle task, to be filtered out. Interrupt and softirq time lands on whichever process was running, which can make your program look as if it made calls it did not. Profiling the Linux kernel itself with perf and kallsyms walks through a copy-heavy workload and the filters that help.
For questions that need in-kernel aggregation, such as a latency histogram between two events at a high event rate, BPF tools aggregate at the source and send only a summary. bpftrace writes them in a line. The two tools complement each other: perf for hardware counters, recordings you can reanalyze, annotate and diff; bpftrace for latency distributions and keyed counts. Using bpftrace and BPF-based profiling alongside perf has a comparison table and the cautions.
Programs that are not C
Everything above assumed native code with symbols. Other languages need one extra step each, and the step is nearly always symbols or stacks.
Rust builds are stripped of line tables by default in release mode and omit frame pointers, so set debug = "line-tables-only" in the release profile and build with RUSTFLAGS="-C force-frame-pointers=yes", or record with --call-graph dwarf. Profiling Rust programs with perf shows the profile configuration and demangling.
Go has its own sampling profiler in pprof that understands goroutines, and perf complements it with the hardware view: pprof names the hot function, and the counters say whether it waits on memory or just runs long. Go keeps frame pointers on the common architectures, so perf record -g works without special flags, provided the binary is not stripped. Profiling Go programs at the machine level puts the two side by side.
Languages with a JIT compiler generate code at run time, which has no file and no symbols. perf reads a text map from /tmp/perf-PID.map to name anonymous code, which Node.js writes with --perf-basic-prof, the JVM writes on request through jcmd PID Compiler.perfmap and Python 3.12 writes with -X perf. For annotation of generated code, the runtime writes a jitdump and perf inject --jit converts it. Profiling JIT-compiled code with perf map files has the details for each runtime.
Comparing runs: did the change help?
A profile of one version tells you where to look. A comparison of two tells you whether you were right. perf diff takes two recordings and prints how each symbol changed:
perf record -F 999 -o old.data ./ledger_old
perf record -F 999 -o new.data ./ledger_new
perf diff old.data new.data
perf diff -c ratio old.data new.dataThe default delta is in percentage points of each run's own total, so when one function gets faster, every other function's share rises, which looks like growth. Use the ratio mode, which compares sample counts, and confirm with wall-clock time from perf stat -r 5, since the diff says what changed and the stopwatch says by how much. Comparing two profiles with perf diff lists the traps. For a picture, the differential flame graph colors each box red where it grew and blue where it shrank, with the shape of the new run:
./difffolded.pl -n old.folded new.folded | ./flamegraph.pl > diff.svgBuilding differential flame graphs to compare two runs covers normalizing stack names and drawing the removed stacks.
Whatever the method, make the comparison fair: same input, same machine, same frequency and event, and a baseline measured twice so you know how much a no-change diff already shows. A difference smaller than that noise is not a result.
Virtual machines, containers and production
Where you run perf limits what it can see. A hypervisor shares each physical core among guests, and the PMU belongs to the core, so unless the hypervisor virtualizes it, the guest sees no hardware counters at all, and perf stat prints <not supported> for cycles. Software events such as task-clock and page-faults work everywhere, and perf record falls back to a timer-based cpu-clock event, which still finds hot functions but loses every hardware insight. Containers share the host kernel, so the real PMU is there and the limits are policy: the host's sysctls, the container runtime's seccomp profile, which blocks perf_event_open unless CAP_PERFMON is granted, and PID namespaces. Hardware counters in VMs and containers lists what survives in each case and the fallbacks.
For production services, a few practices keep profiling safe:
Start with
perf top -por a 99 Hz recording of ten to thirty seconds, with frame pointers, and raise only if counts are too low.Record the sysctl values and capability set with the profile, since a flame graph made with kernel symbols hidden looks as if the kernel does nothing.
Keep the exact binary or a debug-info index by build ID next to every recording, because addresses mean nothing without it.
Prefer a capability on one binary to loosening
perf_event_paranoidmachine-wide.On shared hosts, avoid
-aand heavy DWARF recordings; their data volume and unwinding cost are not free.
When perf is the wrong tool
A good guide says where it stops. perf is a Linux tool, so on macOS you use Instruments, on Windows ETW and Windows Performance Analyzer, and the comparison of all of them is in the complete guide to native profilers. Within Linux, three situations call for something else.
Frame-based or latency-critical work. A game or an audio loop cares about the one bad frame, which sampling averages away. Tracy records the zones you mark with nanosecond timestamps and shows the specific frame on a timeline.
Exact counts and per-call attribution. Sampling cannot tell you a function was called fifty million times, and gprof's averaging gives wrong blame between callers. Callgrind counts every instruction deterministically at a large slowdown, so use it on small inputs and for regression checks.
Heap questions. perf sees allocator functions as CPU time and nothing about lifetimes. Massif and DHAT show who holds memory and which blocks are short-lived or oversized.
There is also a boundary within perf itself. Top-down analysis, perf mem, perf c2c, Intel PT and precise sampling depend on hardware support that your machine, especially a cloud instance, may not have. When a command says unsupported, that is information about the platform, not a failure of your method; fall back to software events and timer sampling and treat the results as relative.
A route through the rest
Read in this order and each post builds on the previous rung.
Beginner. Install perf and profile your first program, then count cycles, instructions and cache misses and find hot functions with perf record and perf report. If your kernel has no matching package, build perf from source.
Intermediate. Find hot instructions with perf annotate, prepare the machine, ship debug symbols, generate flame graphs, profile a running process, and measure branch mispredictions. Language and platform posts: Rust, Go, and VMs and containers.
Advanced. Call graphs, their three methods compared, perf sched, perf trace, perf diff, how sampling works, perf probe and kernel profiling.
Expert. Top-down analysis and its model, perf mem, perf c2c, raw PMU events, JIT maps, Intel PT and bpftrace beside perf.
The measurement discipline in one page
Tools produce numbers, and discipline makes them mean something. Six habits carry most of the weight.
Classify before you locate. perf stat first. IPC, cache misses and branch misses tell you whether to look at instructions, memory or branches, and task-clock against elapsed time tells you whether the CPU is even the right place to look.
Profile what you ship. The same optimization level, the same inputs, the same flags. Add -g and frame pointers, which do not change generated code in any way that matters.
Count the samples. A few thousand support big differences. Raise the frequency or lengthen the run until the boxes you care about hold dozens of samples.
Read clusters, not single lines. Skid moves the blame to the next instruction.
Change one thing, then measure twice. The same two commands before and after, and the stopwatch as the final judge.
Write down the context. Processor model, kernel and perf versions, event names with modifiers, sysctl values, the exact binary. A profile you cannot reproduce is an anecdote.


