Using perf for hardware-level insights
What you'll learn: How to use the Linux perf tool to identify specific lines of code that are slowing down your program by taxing the CPU.
The X-Ray for your code
Imagine your program is a car that isn't reaching its top speed. You could guess why, or you could use a diagnostic tool to see exactly which part of the engine is overheating. On Linux, perf is that diagnostic tool.
Unlike simple timers that tell you how long a program took to run, perf looks at "hardware events." It watches the CPU as it executes your instructions and takes snapshots (samples) of what the program is doing thousands of times per second.
Spotting the "Hotspots"
The most common way to use perf is to find "hotspots"—functions or lines of code where the CPU spends the most time.
Consider this inefficient loop that processes a large array:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100000000
int main() {
int *data = malloc(SIZE * sizeof(int));
long long sum = 0;
// A heavy operation that the CPU will spend time on
for (int i = 0; i < SIZE; i++) {
data[i] = i;
sum += data[i] * 2;
}
printf("Sum: %lld\n", sum);
free(data);
return 0;
}
To profile this, you would compile it with debugging symbols (-g) so perf can map addresses back to your source code, then run:
perf record ./my_program: This runs your code and records performance data into a file namedperf.data.perf report: This opens an interactive dashboard.
Reading the results
When you run perf report, you’ll see a list of functions sorted by "Overhead." If a function shows 80.00%, it means the CPU was busy inside that function 80% of the time.
You can even "annotate" the results. By pressing a on a highlighted function, perf will show you your C code side-by-side with the assembly instructions. It will place red percentages next to the exact lines of code that are stalling the processor. This allows you to stop guessing and start fixing the specific line that is hurting your performance.
Key takeaway
perf record and perf report allow you to pinpoint the exact lines of code where your CPU is spending the most effort.