Sub topic 6
Compulsory, capacity, and conflict misses
This chapter assumes you know what a cache line is, the difference between spatial and temporal locality, and basic C. It also assumes you can read a loop nest and estimate how much memory it touches. Earlier chapters covered those ideas. Here they become a tool for diagnosing why a particular access missed the cache.
Why classify misses at all
A cache miss means the requested line was not in the cache, so the CPU waited for a slower level. Two programs can show the same miss rate for different reasons, and each reason has a different fix. Sorting misses into three kinds tells you which fix to try first.
The classic "three Cs" model sorts every miss into one of these groups:
| Kind | Cause | Typical fix |
|---|---|---|
| Compulsory (cold) | First access to a line ever | Prefetch, or touch fewer lines |
| Capacity | Working set is larger than the cache | Shrink the working set, or block the loops |
| Conflict | Too many lines map to the same set | Change strides, padding, or layout |
Some texts add a fourth C, coherence, for misses caused by other cores invalidating a line. That case is covered in the false sharing chapter and is left out here.
Compulsory misses
A compulsory miss happens the first time a program touches a line. No cache size can avoid it, because the data has never been loaded. A cache of infinite size would still take these misses.
Suppose you sum an array of 1,000,000 int values once. With 64-byte lines, each line holds 16 values. The loop loads about 62,500 lines, and every one of them is a compulsory miss. The cache hit rate is still about 94 percent, because 15 of every 16 accesses hit a line that the first access already loaded.
You cannot remove compulsory misses by rearranging a single pass, but you can reduce their cost:
- Touch fewer lines. Smaller types, packed structs, and splitting hot from cold data all cut the number of lines you must load.
- Overlap the wait. Hardware prefetching hides the latency of sequential first touches. Software prefetch instructions can help with patterns the hardware cannot predict.
- Reuse data before it leaves. If you will read the same data again, do it soon, so the later reads are hits.
Capacity misses
A capacity miss happens when a line was loaded earlier but was evicted because the working set did not fit. The program asks for it again and has to fetch it a second time.
The working set is the amount of distinct data the program touches between two uses of the same line. If you loop over a 64 MiB array ten times and the last-level cache holds 32 MiB, each pass evicts the lines the next pass needs. Every pass takes misses on nearly every line. If the array were 16 MiB, the last pass would mostly hit.
This produces a recognizable pattern. Performance stays flat while the data fits in a level, then drops sharply when the data crosses that level's size. The next program measures it. It reads a buffer repeatedly at several sizes and prints the time per access.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Reads one byte per 64-byte line, repeatedly, over a buffer of 'bytes'. */
static double ns_per_access(size_t bytes, size_t total_accesses) {
volatile unsigned char *buf = malloc(bytes);
if (!buf) return -1.0;
for (size_t i = 0; i < bytes; i++) buf[i] = (unsigned char)i;
size_t lines = bytes / 64;
unsigned long sink = 0;
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (size_t k = 0, i = 0; k < total_accesses; k++) {
sink += buf[i * 64];
if (++i == lines) i = 0;
}
clock_gettime(CLOCK_MONOTONIC, &t1);
free((void *)buf);
if (sink == 12345678UL) puts(""); /* keeps 'sink' observable */
double ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
return ns / (double)total_accesses;
}
int main(void) {
for (size_t kib = 16; kib <= 65536; kib *= 4) {
printf("%8zu KiB: %.2f ns/access\n", kib,
ns_per_access(kib * 1024, 100000000));
}
return 0;
}Expect the time per access to step up near your L1, L2, and L3 sizes. The exact numbers depend on your machine. This access pattern is sequential, so the hardware prefetcher softens the steps. A random access order would show them more sharply.
The fixes for capacity misses all aim to shrink or reorder the working set:
- Use smaller data types or tighter layouts so the same data takes fewer lines.
- Process data in chunks that fit in cache, and finish all work on a chunk before moving on. Blocking, covered in a later chapter, is the general form of this.
- Fuse loops that read the same data, so one pass does the work of two.
Conflict misses
A conflict miss happens when the cache has room overall, but too many of the lines you need compete for the same small group of slots. The working set fits by size, yet lines are evicted anyway.
To see why, recall how a set-associative cache places lines. The cache is divided into sets. The address of a line selects exactly one set, and that set holds a fixed number of lines, called the associativity or the number of ways. A line can live only in its own set. If you touch more lines that map to one set than the set has ways, they evict each other, even when other sets are empty.
For a typical 32 KiB, 8-way L1 data cache with 64-byte lines:
- The cache holds 32768 / 64 = 512 lines.
- With 8 ways, there are 512 / 8 = 64 sets.
- The set index comes from address bits 6 to 11, just above the 6 bits of offset within the line.
Two addresses map to the same set when they differ by a multiple of 64 × 64 = 4096 bytes. That distance is the critical stride for this cache. It is a power of two, which is why power-of-two array sizes are a classic trigger.
A worked example
Consider a column walk over a matrix whose rows are exactly 4096 bytes wide, so each row has 512 doubles. Moving down one column steps 4096 bytes each time, and every element lands in the same set. After 8 rows, the set is full. The ninth access evicts the first line. When the next column starts, it needs the neighbors of lines that were already evicted, so spatial locality is wasted.
The cache is not full. Only one set out of 64 is in use. The miss rate looks like a capacity problem, but the cause is the stride.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 4096
/* Column-wise sum over a ROWS x cols matrix of doubles. */
static double time_walk(size_t cols) {
double *m = calloc((size_t)ROWS * cols, sizeof(double));
if (!m) return -1.0;
double s = 0.0;
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int rep = 0; rep < 20; rep++)
for (size_t j = 0; j < 64; j++)
for (size_t i = 0; i < ROWS; i++)
s += m[i * cols + j];
clock_gettime(CLOCK_MONOTONIC, &t1);
free(m);
if (s == 1.0) puts("");
return (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6;
}
int main(void) {
printf("cols=512 (4096-byte rows): %.1f ms\n", time_walk(512));
printf("cols=520 (padded rows): %.1f ms\n", time_walk(520));
return 0;
}Both calls do the same arithmetic over the same number of elements. The padded version adds 8 doubles, 64 bytes, to each row. Successive rows then land in different sets, and the walk typically runs noticeably faster on a cache like the one described above. The size of the gap varies with the CPU, because lower cache levels and the prefetcher also affect the result.
Common ways to cut conflict misses:
- Pad rows or arrays so the stride is not a multiple of the critical stride.
- Avoid allocating many large buffers at addresses that are the same distance apart, and then touching them in lockstep.
- Reduce the number of streams the inner loop reads at once, so they fit within the available ways.
Telling the three apart in practice
You rarely get a label from the hardware. You infer the cause by changing one thing and watching the result.
- Run the code on a much smaller input. If the miss rate drops sharply, the problem scales with size, which points to capacity.
- If misses persist on a small input that easily fits in cache, suspect conflicts. Try changing the leading dimension by a small amount, such as 8 doubles, and re-measure.
- If the data is touched only once, the misses are mostly compulsory. Look at how many lines you load, and at whether prefetching hides them.
Summary of the model
The three kinds form a ladder of questions. First, was the line ever loaded? If not, the miss is compulsory. Second, would the line have survived in a fully associative cache of the same size? If not, the miss is a capacity miss. Third, if it would have survived in a fully associative cache but not in the real one, the miss is a conflict miss. The ladder also shows the cost order of the fixes: reduce the data first, restructure the loops second, and adjust strides last.
Exercise
A 32 KiB, 8-way L1 cache has 64-byte lines. You walk down a column of a matrix of 4-byte floats whose rows are 2048 floats long. (a) What is the stride in bytes? (b) Does every element map to the same set? (c) Name one change that fixes it.
Show answer
(a) 2048 × 4 = 8192 bytes. (b) The cache has 64 sets, so addresses 4096 bytes apart share a set. 8192 is a multiple of 4096, so every element in the column maps to one set, and only 8 of them can be cached at once. (c) Pad each row, for example to 2064 floats (8256 bytes). The stride is no longer a multiple of 4096, so successive rows spread across different sets.
Exercise
You loop ten times over a 48 MiB array on a CPU with a 32 MiB last-level cache. Which miss type dominates after the first pass, and what is one way to reduce it?
Show answer
Capacity misses dominate, because the working set is larger than the cache and each pass evicts lines the next pass needs. The first pass mostly takes compulsory misses. To reduce the capacity misses, process the array in chunks smaller than the cache and run all ten passes of work on each chunk before moving to the next, or shrink the element type so the array fits.