Sub topic 10
Hardware prefetching and predictable access patterns
This chapter assumes you know what a cache line is, the difference between spatial and temporal locality, and how row-major traversal works. It also assumes you can read basic C.
What the prefetcher does
A cache miss costs on the order of a hundred nanoseconds. A hardware prefetcher hides part of that cost. It is circuitry in the CPU that watches the addresses your program loads. When it sees a pattern, it fetches the next cache lines into cache before your code asks for them.
Prefetching is automatic. You don't call it. You can only make your access pattern easy to recognize, or hard.
Patterns the hardware recognizes
Common prefetchers handle these cases:
- Sequential streams. Addresses that rise (or fall) one cache line at a time. Most CPUs detect these after a few misses.
- Constant strides. Accesses such as every 16th element. Many CPUs track a stride per load instruction.
- Several streams at once. Cores usually follow a limited number of streams. Merging many arrays in one loop can exceed that limit.
Prefetchers generally don't cross a 4 KiB page boundary, because the next virtual page may not map to the next physical page. Each new page can cost a short restart in the stream.
What defeats it
Random access and pointer chasing give the prefetcher nothing to extrapolate from. In a linked list, the address of node k+1 is stored inside node k. The CPU can't know it until node k arrives. Even if the nodes happen to sit in order in memory, the dependent loads still serialize.
Seeing the effect
The program below sums the same 16 million integers twice. The first loop reads them in order. The second reads them in a shuffled order through an index array. Both do the same arithmetic.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N (1u << 24)
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (double)t.tv_sec + (double)t.tv_nsec * 1e-9;
}
int main(void) {
int *data = malloc(N * sizeof *data);
size_t *order = malloc(N * sizeof *order);
if (!data || !order) return 1;
for (size_t i = 0; i < N; i++) { data[i] = 1; order[i] = i; }
srand(1);
for (size_t i = N - 1; i > 0; i--) {
size_t j = (((size_t)rand() << 15) ^ (size_t)rand()) % (i + 1);
size_t tmp = order[i]; order[i] = order[j]; order[j] = tmp;
}
double t0 = now();
long seq = 0;
for (size_t i = 0; i < N; i++) seq += data[i];
double t1 = now();
long rnd = 0;
for (size_t i = 0; i < N; i++) rnd += data[order[i]];
double t2 = now();
printf("sequential: %.3f s (sum %ld)\n", t1 - t0, seq);
printf("shuffled: %.3f s (sum %ld)\n", t2 - t1, rnd);
free(data);
free(order);
return 0;
}Compile it with gcc -O2 prefetch.c -o prefetch. The shuffled loop is typically several times slower. The order array is read sequentially in both cases, so the gap comes from the scattered reads of data.
Writing prefetch-friendly code
- Prefer contiguous arrays over linked nodes when you iterate often.
- Keep strides small and constant. Walk memory in storage order.
- If you must visit items in an irregular order, sort or batch the indices first so addresses rise.
- Avoid loops where each load's address depends on the previous load's result.
Exercise
A list's nodes were allocated one after another, so they sit in ascending address order. Why can summing the list still be slower than summing an array of the same values?
Show answer
Each node's next pointer is stored in the node itself. The CPU can't issue the load for node k+1 until node k has arrived, so the loads form a dependent chain. Each node is also larger than a bare value (it carries a pointer), so fewer values fit per cache line. An array exposes all addresses up front, so the prefetcher and out-of-order execution can overlap the loads.