Skip to content
systemcoding.dev
Performance

Count Cycles, Instructions and Cache Misses With perf stat

Count cycles, instructions and cache misses with perf stat, then read instructions per cycle and miss ratios to tell compute from memory stalls.

6 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the Arm, LLVM and GNU logos.

Before you look for a hot function, find out what kind of slow the program is. A loop that executes too many instructions and a loop that waits on memory look the same in a stopwatch, and they need opposite fixes. perf stat counts hardware events for a whole run and prints them in a few lines, which is enough to tell the two apart. This post uses perf 6.8 on Linux 6.8 with GCC 13 and builds on installing perf and profiling your first program.

Count the default events

Run any command under perf stat and it prints a default set of counters when the command exits. The program here walks an array twice, once in order and once with a large stride, so the two loops differ only in how they touch memory.

stride.cc
#include <stdio.h>
#include <stdlib.h>

#define N (1 << 24)

int main(int argc, char **argv) {
    long stride = argc > 1 ? atol(argv[1]) : 1;
    int *a = calloc(N, sizeof(int));
    if (!a) return 1;
    long total = 0;
    for (int pass = 0; pass < 8; pass++) {
        for (long start = 0; start < stride; start++) {
            for (long i = start; i < N; i += stride) {
                total += a[i];
                a[i] = (int)total;
            }
        }
    }
    printf("%ld\n", total);
    free(a);
    return 0;
}

Both runs touch every element the same number of times, because the middle loop covers each starting offset. Only the order differs. Build it with gcc -O2 -g stride.c -o stride and count:

Shell
perf stat ./stride 1
Text
0

 Performance counter stats for './stride 1':

            121.84 msec task-clock                       #    0.996 CPUs utilized
                 1      context-switches                 #    8.207 /sec
                 0      cpu-migrations                   #    0.000 /sec
            16,452      page-faults                      #  135.034 K/sec
       452,100,318      cycles                           #    3.711 GHz
       601,244,907      instructions                     #    1.33  insn per cycle
       100,663,492      branches                         #  826.186 M/sec
            41,022      branch-misses                    #    0.04% of all branches

       0.122319004 seconds time elapsed

The numbers are an illustration of the format; yours will differ. The total prints 0 because the array starts zeroed and every stored value is the running total, which stays 0. The line to read first is insn per cycle, abbreviated IPC.

Read instructions per cycle

IPC is instructions divided by cycles. A modern core can retire several instructions per cycle when nothing blocks it, so an IPC well above 1 means the core is fed. An IPC well below 1 means cycles passed with little retired, which is the signature of waiting, most often for memory. Now the strided run:

Shell
perf stat ./stride 4096
Text
0

 Performance counter stats for './stride 4096':

           1042.10 msec task-clock                       #    0.999 CPUs utilized
                 3      context-switches                 #    2.879 /sec
                 0      cpu-migrations                   #    0.000 /sec
            16,455      page-faults                      #   15.790 K/sec
     3,861,207,112      cycles                           #    3.705 GHz
       601,311,540      instructions                     #    0.16  insn per cycle
       100,670,018      branches                         #   96.602 M/sec
            45,310      branch-misses                    #    0.05% of all branches

       1.043002118 seconds time elapsed

Same instruction count, about eight times the cycles, IPC down from 1.33 to 0.16. The work did not change; the waiting did. That conclusion comes from the counters alone, before any source is opened. Treat the exact ratio as machine specific. The direction is what generalizes: more cycles for the same instructions means stalls.

Ask for specific events

The default list varies by processor. Name events with -e to count what you want, comma separated. The generic cache events are cache-references and cache-misses, plus the L1 data cache pair L1-dcache-loads and L1-dcache-load-misses:

Shell
perf stat -e cycles,instructions,cache-references,cache-misses,L1-dcache-loads,L1-dcache-load-misses ./stride 4096
Text
0

 Performance counter stats for './stride 4096':

     3,858,913,440      cycles
       601,298,772      instructions                     #    0.16  insn per cycle
       201,330,115      cache-references
       168,942,830      cache-misses                     #   83.91% of all cache refs
       402,653,964      L1-dcache-loads
       201,100,562      L1-dcache-load-misses            #   49.94% of all L1-dcache accesses

       1.040118772 seconds time elapsed

Two ratios matter. cache-misses as a share of cache-references is the last-level cache miss ratio on most Intel and AMD cores, so 83.91% here says most of the references go to main memory. The L1 ratio says half of the loads miss the smallest cache. Run the same command with ./stride 1 and both ratios fall sharply, because sequential access lets the hardware prefetcher stay ahead.

The meaning of the generic names is defined per architecture by the kernel's perf_event_open(2) documentation, not by the tool. cache-misses maps to the last-level cache on x86, but another architecture can map it differently. When a figure will drive a decision, check the mapping with perf list and consider the raw event names covered in using hardware event names and raw PMU events.

Count more than one run

One run is one sample. Use -r to repeat the command and report a mean with its spread:

Shell
perf stat -r 5 -e cycles,instructions ./stride 1
Text
 Performance counter stats for './stride 1' (5 runs):

       452,330,114      cycles                           ( +-  0.21% )
       601,244,950      instructions                     #    1.33  insn per cycle            ( +-  0.00% )

          0.122140 +- 0.000380 seconds time elapsed  ( +-  0.31% )

The +- figures are the variation across runs. Instruction counts are almost exactly repeatable for a deterministic program; cycle counts are noisier because of frequency changes, other processes and cache state. If the spread is larger than the difference you are chasing, you have not measured a difference yet.

Count only what you care about

Add -p PID to attach to a running process for a bounded time, or -a to count the whole machine. Append -- and a command, or sleep 5, to set the window:

Shell
perf stat -e cycles,instructions -p 4242 -- sleep 5
Text
 Performance counter stats for process id '4242':

     1,204,556,310      cycles
     1,877,219,046      instructions                     #    1.56  insn per cycle

       5.001203412 seconds time elapsed

The PID is a placeholder. Counting a live service for a few seconds is a safe first look because the counters are read, not sampled.

When these counters mislead

Counters report totals, not locations: a bad IPC says the run waited, never where. Hand over to perf record for that. A low IPC can also come from a workload that is meant to wait, such as a program that blocks on I/O; wall-clock task-clock against time elapsed shows that quickly. And inside a virtual machine the hardware counters may print <not supported>, which is covered in what perf can and cannot see in VMs.

Why cache misses follow the access pattern

The strided run misses so often because of how the hardware moves data. Memory is read in cache lines, 64 bytes on current x86 cores, and the sequential loop uses every int in a line before moving on, so sixteen loads share one line fetch. A stride of 4096 ints is 16 KiB between touches, so every load lands on a new line and often on a new page, and the hardware prefetcher, which watches for regular small strides, cannot hide the latency. Nothing in the instruction stream changed. The instruction count stayed at about 601 million in both runs, and only the time each load waited differed.

That is why instruction count alone is a poor performance metric and cycles alone is a poor diagnosis. Together they separate the two families of problem. High instructions with healthy IPC says reduce work: a better algorithm, fewer calls, vectorization. Low IPC with a high miss ratio says reduce data movement: better layout, blocking, smaller types, or touching memory in order. Branch mispredictions are the third family and show up in the branch-misses line, which measuring branch mispredictions with perf stat takes further.

A caution about reading ratios in isolation: a program can have a terrible miss ratio on a few references and still be fast, because the count of misses, not the ratio, sets the cost. Always read the ratio next to the absolute event count and the run time.

Event names differ between processors

The generic names such as cycles and instructions are aliases the kernel maps onto whatever the processor offers. On Intel they resolve to architectural events, on AMD to the closest equivalent, and on Arm to the matching PMU event. The same alias can therefore count slightly different things on two machines, so a figure from a laptop and a figure from a server are comparable only in direction. Run perf list to see which names your hardware accepts and which are marked as software events, and keep the exact event list with any result you intend to compare later.

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.