Sub topic 12
Associativity and Conflict Misses from Power-of-Two Strides
This chapter assumes you know how a cache line works, the difference between capacity and conflict misses, and how row-major arrays are laid out. It explains why a loop can run slowly even when its data fits in the cache, and why padding an array can fix it.
Why a cache cannot put a line anywhere
A cache cannot store a line in any free slot, because searching every slot on each load would be too slow and use too much power. The hardware restricts where each memory line may go. The cache is divided into sets, and each set holds a small number of lines called ways. A cache with W ways per set is W-way set-associative.
The hardware picks the set from the address bits. A 64-byte line makes the low 6 address bits the offset inside the line. The next bits are the set index, and the remaining high bits are the tag stored to identify the line.
set index = (address / line_size) mod number_of_setsA line can go into any way of its set, and only that set. When the set is full, one line is evicted even if every other set is empty.
Computing the geometry
The number of sets follows from the cache size, the ways, and the line size.
sets = cache_size / (ways * line_size)
critical stride = sets * line_sizeTwo addresses whose distance is a multiple of the critical stride land in the same set. The table shows typical values. Check your own CPU with lscpu or getconf -a | grep CACHE on Linux.
| Cache | Ways | Line | Sets | Critical stride |
|---|---|---|---|---|
| 32 KiB L1 data | 8 | 64 B | 64 | 4096 B |
| 48 KiB L1 data | 12 | 64 B | 64 | 4096 B |
| 1 MiB L2 | 16 | 64 B | 1024 | 65536 B |
Many L1 caches have 64 sets because of a design constraint. The set index is taken from bits that lie within the 4 KiB page offset. The cache can then start its lookup before address translation finishes. For that reason 4096 bytes is a critical stride on a large number of CPUs.
How a power-of-two stride causes conflicts
Suppose a matrix of double has 512 columns, so each row is 4096 bytes. Walking down one column touches addresses 4096 bytes apart. Every access has the same set index, so all of them compete for the 8 ways of one set. The other 63 sets sit unused.
The column might have 256 elements, which is only 16 KiB of lines. That is half the L1 size, so a capacity miss does not explain the slowdown. But only 8 of the 256 lines can live in L1 at once. On the next pass over the column, the earlier lines have been evicted. Each access misses in L1 and has to be served from L2.
The block above is a placeholder. The diagram follows in its proper fenced form.
This is a conflict miss. A fully associative cache of the same size would have no misses on the second pass, which is the definition of the conflict category.
A benchmark you can run
The program below reads one element from each of 256 rows, many times. It uses the same data volume for both runs. Only the row length, called the leading dimension, differs: 512 doubles (4096 bytes) and 520 doubles (4160 bytes).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 256
#define REPEAT 200000
static double now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}
static double run(size_t ld) {
double *m = calloc(ROWS * ld, sizeof(double));
if (m == NULL) {
perror("calloc");
exit(1);
}
for (size_t i = 0; i < ROWS * ld; i++)
m[i] = 1.0;
const volatile double *p = m; /* volatile keeps every load */
double acc[8] = {0}; /* independent sums hide add latency */
double t0 = now();
for (int r = 0; r < REPEAT; r++)
for (size_t i = 0; i < ROWS; i += 8)
for (size_t k = 0; k < 8; k++)
acc[k] += p[(i + k) * ld];
double t1 = now();
double total = 0.0;
for (int k = 0; k < 8; k++)
total += acc[k];
printf("ld=%zu doubles (%zu bytes): %.3f s (checksum %.0f)\n",
ld, ld * sizeof(double), t1 - t0, total);
free(m);
return t1 - t0;
}
int main(void) {
run(512);
run(520);
return 0;
}Compile with gcc -O2 -o stride stride.c and run it. On many x86 CPUs the 512 case is measurably slower. The L2 absorbs the misses, so expect a moderate slowdown rather than a main-memory-sized one. The size of the gap depends on your CPU, and some processors hash the index bits and show little difference. Run each case several times before trusting a result.
Confirming the cause with counters
A timing difference does not prove a conflict. On Linux, compare L1 miss counts for the two variants.
perf stat -e L1-dcache-loads,L1-dcache-load-misses ./strideIf the 4096-byte pitch shows a much higher miss rate while the working set is far smaller than L1, conflicts are the likely cause. Sweeping the pitch from 4000 to 4200 bytes in steps of 64 and plotting time is another good test. The slowdown appears as spikes at multiples of the critical stride.
Fixes
- Pad the leading dimension. Allocate rows of
N + 8doubles (one extra line) instead ofN. Consecutive rows then shift by one set. Keep the logical width separate from the stored pitch in your indexing code. - Choose tile sizes with conflicts in mind. In blocked algorithms such as the transpose from the blocking chapter, a tile of a power-of-two matrix still has rows spaced at the critical stride. A 32-row tile fits easily in 8 ways only if its rows map to different sets. Padding the matrix, or copying the tile into a small contiguous buffer, avoids the problem.
- Offset simultaneous arrays. In a loop like
a[i] = b[i] + c[i], large page-aligned allocations can have the same low address bits. All three streams then hit one set at the same time. Adding a small offset, such as a few cache lines, to the base ofbandcseparates them. - Avoid power-of-two row counts only when the stride is the issue. The row count does not matter. The byte distance between accesses does.
Edge cases
- Higher associativity helps, not eliminates. A 16-way cache tolerates twice as many colliding lines, but a column of 256 rows still overflows it.
- Shared caches. In a shared L3, other threads' data competes for the same sets, so conflict behavior can change from run to run.
- Hashed indexing. Some L2 and L3 caches XOR upper address bits into the index, which makes power-of-two strides less harmful. You cannot assume this, and it varies by vendor.
- Fixing the traversal is better. If you can walk the data in storage order, as in the traversal chapter, there is no stride to fix.
Exercise
A CPU has a 64 KiB, 4-way set-associative L1 data cache with 64-byte lines. What is the critical stride? A program reads one double from each of 100 rows of a matrix whose rows are 16384 bytes long, and repeats this many times. Will it suffer conflict misses, and what is a simple fix?
Show answer
Sets = 65536 / (4 64) = 256, so the critical stride is 256 64 = 16384 bytes. The row pitch equals the critical stride, so all 100 rows map to one set that holds only 4 lines. Almost every access misses in L1 after the first pass even though the 100 lines (6400 bytes) are far smaller than the cache. The simple fix is to pad each row by one cache line (64 bytes), giving a pitch of 16448 bytes, so successive rows move to successive sets.