Sub topic 11
Measuring Cache Behavior Without Fooling Yourself
This chapter assumes you can read C and C++, know what a cache line is, and have seen the row-major versus column-major example from earlier chapters. Here you learn how to measure cache effects and avoid the usual traps.
Why measurements mislead
A cache-friendly change often looks obvious in theory. A benchmark can still hide it or invent it. Three problems cause most errors:
- The compiler removes your work. If the result is never used, the optimizer may delete the loop.
- The first run is not typical. Page faults and cold caches inflate the first iteration.
- The data size is wrong. An array that fits in L2 cache tells you nothing about main memory behavior.
A minimal benchmark
The program below times the row-major and column-major sums. It repeats each run and prints the result, so the compiler cannot discard the loops.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 4096
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec * 1e-9;
}
static double sum_row(const double (*m)[N]) {
double s = 0.0;
for (size_t i = 0; i < N; i++)
for (size_t j = 0; j < N; j++)
s += m[i][j];
return s;
}
static double sum_col(const double (*m)[N]) {
double s = 0.0;
for (size_t j = 0; j < N; j++)
for (size_t i = 0; i < N; i++)
s += m[i][j];
return s;
}
int main(void) {
double (*m)[N] = malloc(sizeof(double[N][N]));
if (!m) return 1;
for (size_t i = 0; i < N; i++)
for (size_t j = 0; j < N; j++)
m[i][j] = 1.0;
double (*fn[2])(const double (*)[N]) = { sum_row, sum_col };
const char *name[2] = { "row-major", "col-major" };
for (int k = 0; k < 2; k++) {
double best = 1e9, result = 0.0;
for (int rep = 0; rep < 5; rep++) {
double t0 = now();
result = fn[k](m);
double t1 = now();
if (t1 - t0 < best) best = t1 - t0;
}
printf("%s: %.3f s (sum=%.0f)\n", name[k], best, result);
}
free(m);
return 0;
}Compile with gcc -O2 bench.c -o bench. The matrix is 128 MiB, far larger than any cache. The program fills it first, so pages are already mapped. It reports the best of five runs, which filters out interruptions from other processes.
Reading hardware counters
Timing shows that something changed. Hardware counters show why. On Linux, perf stat reads them:
perf stat -e cache-references,cache-misses,instructions,cycles ./benchCompare the miss counts and the ratio of cache-misses to cache-references. Event names and meanings differ between CPU vendors. On many Intel chips, cache-misses counts last-level cache misses only. Check your CPU's documentation before you compare numbers across machines.
Checklist
- Use a data size larger than the cache level you care about.
- Consume the result so the optimizer keeps the code.
- Warm up, repeat, and report the best or median time.
- Change one variable at a time.
- Confirm with counters, not timing alone.
Exercise
Your benchmark shows a linked-list sum and an array sum taking the same time with 1,000 elements. Does this prove that layout does not matter? What would you change?
Show answer
No. 1,000 elements fit entirely in L1 or L2 cache, so pointer chasing is cheap. Increase the element count until the data exceeds the last-level cache, shuffle the list nodes in memory if they were allocated in order, and compare again, ideally confirming with cache-miss counters.