Install perf and Profile Your First Program
Install perf from your distribution, check it matches the kernel, then run perf stat and perf record on a small C program to see where time goes.

A program that feels slow is a guess until something measures it. On Linux the measuring tool that ships with the kernel is perf, and the first run takes about five minutes: install the package, point it at a small program, and read two reports. This post does that on Ubuntu 24.04 with kernel 6.8 and GCC 13, and the same commands work on any recent distribution once the package name is swapped. If you want the whole map of what perf can do afterwards, the complete guide to profiling on Linux with perf is the hub this post feeds into.
Install the package that matches your kernel
perf is built from the kernel source tree under tools/perf, and it talks to the running kernel through the perf_event_open(2) system call. Because the tool and the kernel share an event vocabulary, a distribution ships the tool in a package named after the kernel version.
On Ubuntu and Debian the package is linux-tools-generic, plus a second package keyed to the exact kernel you booted:
sudo apt update
sudo apt install linux-tools-generic linux-tools-$(uname -r)On Fedora the package is perf, and on Arch it is perf as well:
sudo dnf install perf
sudo pacman -S perfCheck that it runs and reports a version close to your kernel:
perf --version
uname -rperf version 6.8.12
6.8.0-45-genericThe exact numbers on your machine will differ. What matters is that the first two numbers agree. A perf binary far older than the kernel fails on newer events, and one far newer can ask the kernel for fields it does not know. When the Ubuntu wrapper prints a complaint that perf for your kernel is not installed, the linux-tools-$(uname -r) package above is the fix. If your distribution has no matching package at all, building perf from kernel source is the fallback.
Allow unprivileged profiling
By default many distributions restrict what a normal user can measure through the sysctl kernel.perf_event_paranoid. Read it:
cat /proc/sys/kernel/perf_event_paranoid4The upstream kernel defaults to 2, which still lets you profile your own user-space code. Debian and Ubuntu carry a patch that adds levels 3 and 4, where 3 denies all unprivileged perf_event_open use. If you see 3 or higher, run the examples with sudo or lower the value for this boot:
sudo sysctl -w kernel.perf_event_paranoid=1That command changes the setting until reboot. The kernel documents every level in its perf security guide, and preparing a Linux box for profiling covers what each level allows and what to set permanently.
A program worth profiling
A profiler needs something that spends measurable time. This program sums a large array in two ways, one of which wastes work on purpose.
#include <stdio.h>
#include <stdlib.h>
#define N 20000000
static long sum_plain(const int *a, long n) {
long total = 0;
for (long i = 0; i < n; i++) {
total += a[i];
}
return total;
}
static long sum_slow(const int *a, long n) {
long total = 0;
for (long i = 0; i < n; i++) {
for (int k = 0; k < 8; k++) {
total += (a[i] ^ k) - k;
}
}
return total;
}
int main(void) {
int *a = malloc(sizeof(int) * N);
if (!a) return 1;
for (long i = 0; i < N; i++) a[i] = (int)(i % 1000);
long x = sum_plain(a, N);
long y = sum_slow(a, N);
printf("%ld %ld\n", x, y);
free(a);
return 0;
}Compile it with debug information and with the frame pointer kept, so later reports can name functions and lines. Optimization stays on, because profiling an unoptimized build tells you about the wrong program.
gcc -O2 -g -fno-omit-frame-pointer sum.c -o sumRunning it prints the two sums:
9995000000 79960000000The numbers are deterministic for this input, which makes a quick sanity check before measuring.
First measurement with perf stat
perf stat runs the program and prints counters from the processor's performance monitoring unit and the kernel. It is the cheapest overview you can get.
perf stat ./sum9995000000 79960000000
Performance counter stats for './sum':
215.40 msec task-clock # 0.998 CPUs utilized
2 context-switches # 9.285 /sec
0 cpu-migrations # 0.000 /sec
19,610 page-faults # 91.040 K/sec
812,334,501 cycles # 3.771 GHz
1,421,872,190 instructions # 1.75 insn per cycle
0.215902381 seconds time elapsedThe figures above are an example of the format, and your machine will print different ones. Read the shape of it: task-clock is the time the process spent on a CPU, page-faults counts how often it touched memory the kernel had to map first, and the last two lines give instructions per cycle (IPC). An IPC near or above 1 on a simple loop is normal; a value far below 1 suggests the processor is waiting, usually on memory. Counters such as cycles appear only when hardware events are available, which they are not in many virtual machines (see what perf can and cannot see in VMs).
Second measurement: where the time goes
perf stat says how much; perf record says where. It samples the program at a fixed rate and saves the sampled instruction addresses to perf.data in the current directory.
perf record -F 999 ./sum9995000000 79960000000
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.052 MB perf.data (203 samples) ]-F 999 asks for roughly 999 samples per second. Picking 999 rather than 1000 avoids landing in lockstep with timers that fire at round numbers. The report turns those samples into a ranked list of functions:
perf report --stdio Overhead Command Shared Object Symbol
........ ....... ............. ......
88.67% sum sum [.] sum_slow
9.36% sum sum [.] main
1.97% sum sum [.] sum_plainHere sum_slow owns about nine tenths of the samples, which matches what the source says: it does eight times the work per element. The [.] marks a user-space symbol, and [k] would mark a kernel one. Your percentages will differ, but the order should hold. The compiler may inline sum_plain into main at higher optimization levels, in which case the time shows up under main; that is one reason to build with -g and read the call graph rather than trust names alone.
What to look at next
You now have a measure-then-locate loop. Count with perf stat for cycles, instructions and cache misses to see whether the program is compute bound or waiting. Rank functions with perf record and perf report in more depth. Then drop to instruction level with perf annotate to see exactly which lines inside sum_slow are hot.
When this is not enough
A short run can give too few samples to trust. Two hundred samples is enough to see a nine-to-one split, not enough to rank functions that differ by a point or two. Raise the frequency, lengthen the run or repeat it. And if the program spends its time blocked on disk or locks rather than computing, CPU sampling will not show it: the process is not on a CPU, so no samples land. That case needs off-CPU analysis, not more perf record time.
Reading time in the right units
Two clocks appear in the perf stat output and they answer different questions. task-clock is CPU time the process consumed, summed over all its threads, so a four-thread program can report more task-clock than elapsed time. The time elapsed line is wall-clock time from start to exit. When the two are close and CPUs utilized is near 1, the program was running the whole time on one core. When elapsed time is much larger than task-clock, the process spent the difference waiting, on disk, a lock, the network or a sleep. That single comparison decides whether CPU profiling is the right tool at all, and it costs nothing to check before you record anything.
Build flags matter for what you read afterwards. -O2 produces the code that ships, -g adds line tables without changing the generated code, and -fno-omit-frame-pointer spends one register to keep a reliable chain of return addresses, which later makes call graphs cheap. If you profile a build with a different optimization level than production, you are measuring a different program, and the hot function may not even exist after inlining.


