Sub topic 11
Measuring cache behavior without fooling yourself
This chapter assumes you can read C and C++, know the cache line and locality ideas from earlier chapters, and can use a Linux command line. You will learn how to time code reliably, how to read hardware counters, and which mistakes make a benchmark report something other than what you meant to test.
Why measurement goes wrong
Cache effects are large, often 5x to 50x between a good and a bad layout. That makes them easy to see, but it also makes mistakes easy to confuse with real effects. A benchmark can show a big difference for reasons that have nothing to do with the cache behavior you care about.
The common failure modes are:
- The compiler removes or rewrites the work you wanted to time.
- The first run pays one-time costs (page faults, cold caches, CPU frequency ramp-up) that later runs do not.
- The data set is too small, so everything fits in cache and the layouts look identical.
- The data set is built in a way that does not match real use, such as a linked list whose nodes were allocated in order and so happen to be adjacent.
- One run is treated as the answer, although timings vary from run to run.
Choose the working-set size on purpose
The working set is the amount of memory the loop touches repeatedly. Whether it fits in L1, L2, L3, or only in main memory decides what you measure. A single size tells you little. Sweep the size and look at the shape.
The program below sums an array of different sizes and prints nanoseconds per element. Expect the cost per element to step up as the size passes each cache level.
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <vector>
// Prevents the compiler from deleting the result as dead code.
static volatile std::uint64_t sink;
static std::uint64_t sum(const std::vector<std::uint32_t>& v) {
std::uint64_t s = 0;
for (std::uint32_t x : v) s += x;
return s;
}
int main() {
using clock = std::chrono::steady_clock;
for (std::size_t kib = 4; kib <= 256 * 1024; kib *= 4) {
std::size_t n = kib * 1024 / sizeof(std::uint32_t);
std::vector<std::uint32_t> v(n, 1); // touching the data also faults in pages
std::size_t reps = (64u * 1024 * 1024) / n + 1; // roughly constant total work
sink = sum(v); // warm-up pass, not timed
auto t0 = clock::now();
for (std::size_t r = 0; r < reps; ++r) sink = sum(v);
auto t1 = clock::now();
double ns = std::chrono::duration<double, std::nano>(t1 - t0).count();
std::printf("%8zu KiB %6.3f ns/element\n", kib, ns / (double(reps) * n));
}
}A sequential sum is a gentle test. Hardware prefetching hides much of the latency, so the steps may be small. To see the real latency of each level, use a dependent chain of loads, such as walking a randomly shuffled cycle of indices, where each load needs the previous result.
Stop the compiler from fooling you
An optimizing compiler is allowed to change your code in any way that preserves the visible result. If the result is never used, the whole loop can disappear. A benchmark that reports 0.0 ns per element has usually measured nothing.
Three habits help:
- Use the result. Store it in a
volatilevariable, print it, or use a benchmark library'sDoNotOptimizehelper. - Look at the assembly or the compiler's optimization report for the hot loop. Check that the loop exists and that the work you meant to time is still in it.
- Compile with the optimization level you ship, such as
-O2. A debug build measures a different program.
Also watch for the opposite problem. The compiler may vectorize one layout and not the other, so your result compares code generation, not caches. That is sometimes a legitimate finding, because layout does affect vectorization. Just do not credit it all to cache misses.
Warm up, repeat, and report the spread
The first pass over fresh memory triggers page faults, because the operating system maps pages lazily. The CPU may also be running at a lower clock speed. Run a warm-up pass and discard it. Then run many repetitions and report the median and the spread (minimum and maximum, or a percentile), not a single number.
The minimum is useful for isolating the cost of the code itself, because noise from other processes only adds time. The median describes typical behavior. If the spread is larger than the difference you are trying to show, you have not shown it.
Reduce noise where you can:
- Pin the process to one core with
taskset -c 2 ./bench. - Close other heavy programs.
- On a laptop, plug in the power and avoid thermal throttling.
- Run the variants interleaved (A, B, A, B) instead of all of A and then all of B, so slow drift in clock speed affects both equally.
Build realistic data
The data layout that your benchmark creates decides what it measures. A linked list built by allocating nodes in a tight loop often gets nodes at increasing addresses, so traversal looks almost sequential and the hardware prefetcher helps. A list that has lived in a real program, with inserts, deletes, and other allocations, is scattered.
To model that, allocate the nodes first and then link them in shuffled order. Likewise, for hash tables and trees, use keys and access sequences that resemble production. Sorted keys and random keys can give very different results for the same structure.
Read hardware counters
Timing tells you that something is slow. Counters help show why. On Linux, perf stat reads the CPU's performance monitoring counters:
perf stat -e cycles,instructions,cache-references,cache-misses,L1-dcache-load-misses ./benchWhich events exist depends on the CPU and kernel. Run perf list to see them. In virtual machines and some cloud instances, hardware counters may be unavailable.
Interpret the numbers carefully:
| Number | What it tells you | Caution |
|---|---|---|
| Instructions per cycle (IPC) | Low IPC, such as under 1, suggests the CPU is stalled waiting, often on memory | Branch mispredictions also lower IPC |
| `L1-dcache-load-misses` | Loads that missed the first-level cache | A miss that hits in L2 is cheap, so a high count is not automatically a problem |
| `cache-misses` | Usually last-level cache misses, though the exact meaning varies by CPU | Compare it with `cache-references`, and treat it as a rough signal |
| Miss rate | Misses divided by accesses | A high rate on a rarely executed path does not matter |
Compare counters between two variants of the same program, not against a universal threshold. Also remember that the counters include everything the process does, including startup and data setup. To limit the measurement to the hot region, make that region dominate the run time, or use perf record and perf annotate to see which instructions the stalls land on.
Prefetchers complicate the picture. A sequential loop can show many L1 misses yet run fast, because the prefetcher brings lines in early. The miss count says the data was not already in L1. It does not say the CPU waited.
A checklist before you trust a result
- Does the timed region produce a result that is used?
- Is the build optimized the way production is?
- Did you discard a warm-up run and repeat enough times to see the spread?
- Does the working set match the case you care about (L1, L3, or main memory)?
- Does the data layout, such as allocation order and key order, resemble real use?
- Does the difference exceed the run-to-run noise?
- Do the counters agree with the story you are telling?
If the answer to any of these is no, fix the benchmark before drawing conclusions about the layout.
Exercise
You benchmark a linked list against an array, both holding 1,000 integers. The list is built by calling new in a loop, and both sum in about the same time. A colleague says this proves cache layout does not matter. Give two reasons the result is misleading and one change that would fix it.
Show answer
First, 1,000 integers (a few KiB for the array, tens of KiB for the list) fit in L1 or L2, so almost every access hits cache for both layouts and no layout difference can appear. Second, nodes allocated in a tight loop usually sit at increasing addresses, so the list is nearly sequential in memory and the prefetcher helps. Fix: raise the element count well past the last-level cache (for example tens of millions) and link the nodes in a shuffled order, then repeat the measurement with a warm-up and report the median and spread.
Exercise
A benchmark of a loop reports 0.0 ns per element at -O2 but 1.2 ns per element at -O0. What is the likely cause and how do you check it?
Show answer
At -O2 the compiler probably removed the loop because its result is never used (dead code elimination), so nothing was timed. Check by inspecting the generated assembly for the loop, and fix it by consuming the result, for example storing it in a volatile variable or passing it to a DoNotOptimize helper. Do not fall back to -O0 as the answer, since that measures unoptimized code.