While optimizing software, you often want detailed performance information, such as cache hit rates, branch misprediction rates, and instructions per cycle. On Linux, perf stat allows you to count cycles, instructions, and L1 data cache misses:

1
perf stat -e cycles,instructions,L1-dcache-load-misses ./my_program

However, since perf stat reports total counts for the entire program, it is not suited for profiling specific code regions. For example, even if you only want to measure compute_kernel() in the following program, the perf stat results also include counts from initialize().

1
2
3
4
5
...
initialize(data, n);     // Preprocessing

compute_kernel(data, n); // Main processing
...

To address this issue, I developed perf-counter, a library for measuring performance events within specific code regions.

This article introduces the basics of perf-counter. More practical usage and the internal implementation will be covered in other articles.

How to Use perf-counter

Measuring performance with perf-counter consists of four steps:

  1. Open a counter for the event you want to measure
  2. Enable the counter
  3. Read the counter value before and after the target code region
  4. Disable and release the counter

The following example measures the number of cycles compute_kernel() takes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 1. Open a cycle counter
struct perf_counter pc = perf_counter_open_by_id(
    PERF_TYPE_HARDWARE,       // event_type
    PERF_COUNT_HW_CPU_CYCLES, // event_config
    -1                        // group_fd
);

// Check if the counter was opened successfully
if (!perf_counter_is_valid(&pc)) {
    fprintf(stderr, "Failed to open a cycle counter.\n");
    return 1;
}

// 2. Enable the counter
perf_counter_enable(&pc); // Start measuring the event

// 3. Read the counter value before and after calling compute_kernel()
uint64_t start = perf_counter_read(&pc);
compute_kernel();
uint64_t end = perf_counter_read(&pc);

// Print the number of cycles taken by compute_kernel()
printf("cycles: %lu\n", end - start);

// 4. Disable and release the counter
perf_counter_disable(&pc); // Stop measuring the event
perf_counter_close(&pc);

The arguments of perf_counter_open_by_id(event_type, event_config, group_fd) are as follows:

  • event_type and event_config: Specify the event to measure using a pair of type and config described in perf_event_open(2).
  • group_fd: Specify -1 to measure a single event. To measure multiple events simultaneously, open the first counter with -1 and the others with its fd.

Here are some examples of event_type and event_config combinations:

event_type event_config Description
PERF_TYPE_HARDWARE PERF_COUNT_HW_CPU_CYCLES Number of cycles
PERF_TYPE_HARDWARE PERF_COUNT_HW_INSTRUCTIONS Number of instructions executed
PERF_TYPE_HARDWARE PERF_COUNT_HW_BRANCH_INSTRUCTIONS Number of branch instructions
PERF_TYPE_HARDWARE PERF_COUNT_HW_BRANCH_MISSES Number of branch mispredictions
PERF_TYPE_SOFTWARE PERF_COUNT_SW_PAGE_FAULTS Number of page faults

Opening a Counter by Event Name

Depending on the event, you may need to combine multiple constants to create event_config. For example, measuring L1 data cache misses requires three constants, which is somewhat cumbersome.

1
2
3
4
5
6
uint64_t config =
    PERF_COUNT_HW_CACHE_L1D
    | (PERF_COUNT_HW_CACHE_OP_READ << 8)
    | (PERF_COUNT_HW_CACHE_RESULT_MISS << 16);

struct perf_counter pc = perf_counter_open_by_id(PERF_TYPE_HW_CACHE, config, -1);

In such cases, it is easier to open a counter by event name with perf_counter_open_by_name(). It is available when perf-counter is built with libpfm4. For L1 data cache misses, specify perf::L1-DCACHE-LOAD-MISSES:

1
struct perf_counter pc = perf_counter_open_by_name("perf::L1-DCACHE-LOAD-MISSES", -1);

You can list the available event names with list_all_events.c, an example program bundled with perf-counter. To build the program, see “Building and Running” below.

1
./build/examples/list_all_events events.txt  # Save the list of events to events.txt

Each line of the output consists of an event name and its description.

1
2
3
4
5
...
perf::L1-DCACHE-LOADS # L1 cache load accesses

perf::L1-DCACHE-LOAD-MISSES # L1 cache load misses
...

perf_counter_open_by_name() also makes it easy to measure processor-specific events. For example, on an AMD Ryzen 7 4700U (Zen 2), you can count retired SSE/AVX floating-point multiply operations.

1
2
struct perf_counter pc = perf_counter_open_by_name(
    "amd64_fam17h_zen2::RETIRED_SSE_AVX_FLOPS:MULT_FLOPS", -1);

Example: Measuring FMA Instruction Performance

As a practical example, let’s calculate the latency and throughput of 256-bit FMA (Fused Multiply-Add) instructions. We use perf-counter to count the cycles needed to execute the instructions and then calculate the ratio between cycles and instructions. For the complete code, refer to perf_avx2_fma.cpp.

Measurement Method

Latency is measured by running a long dependency chain of instructions. They execute one at a time because each instruction must wait for the previous one to complete. Dividing the elapsed cycles by the number of instructions gives the latency: how many cycles a single instruction takes (CPI).

1
2
3
4
vfmadd231ps ymm0, ymm1, ymm1  ; ymm0 = ymm0 + ymm1 * ymm1
vfmadd231ps ymm0, ymm1, ymm1  ; ymm0 = ymm0 + ymm1 * ymm1
vfmadd231ps ymm0, ymm1, ymm1  ; ymm0 = ymm0 + ymm1 * ymm1
...
Latency measurement

Latency measurement

Throughput is measured by running many independent instructions, which can execute in parallel. Dividing the number of instructions by the elapsed cycles gives the throughput: how many instructions can be executed per cycle (IPC).

1
2
3
4
vfmadd231ps ymm1, ymm0, ymm0  ; ymm1 = ymm1 + ymm0 * ymm0
vfmadd231ps ymm2, ymm0, ymm0  ; ymm2 = ymm2 + ymm0 * ymm0
vfmadd231ps ymm3, ymm0, ymm0  ; ymm3 = ymm3 + ymm0 * ymm0
...
Throughput measurement

Throughput measurement

We run each test 10 times after three warm-up runs and use the minimum cycle count to eliminate noise from OS scheduling and interrupts.

Building and Running

To build the example programs, set PERF_COUNTER_BUILD_EXAMPLES to ON:

1
2
3
cmake -B build -DCMAKE_BUILD_TYPE=Release -DPERF_COUNTER_BUILD_EXAMPLES=ON
cmake --build build
./build/examples/perf_avx2_fma

Results

Environment: AMD Ryzen 7 4700U (Zen 2), GCC 15.2.1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
AVX2 vfmadd231ps - Latency
  Instructions : 1200000
  Best Cycles  : 6000062
  CPI          : 5.000
  IPC          : 0.200

AVX2 vfmadd231ps - Throughput
  Instructions : 1200000
  Best Cycles  : 600066
  CPI          : 0.500
  IPC          : 2.000

The results show a latency of 5.000 cycles and a throughput of 2.000 instructions per cycle. These values match those reported on uops.info.

References