Sub topic 10
Hardware prefetching and predictable access patterns
This chapter assumes you know what a cache line is and how misses cost time, and that you can read C. Earlier chapters showed that sequential traversal is fast. Here you will see one mechanism behind that: the CPU guesses which lines you will need next and fetches them early. Knowing how it guesses tells you which access patterns it can help with and which it cannot.
What a hardware prefetcher does
A hardware prefetcher is circuitry in the CPU that watches the addresses your program loads and issues cache-line fetches before the program asks for them. If the guess is right, the line is already in cache when the load executes, and the memory latency is hidden.
Prefetchers do not understand your code. They only see a stream of addresses, so they look for simple regularities:
- Streams: consecutive lines, such as
a[0],a[1],a[2]in an array. The prefetcher fetches the next several lines ahead. Many CPUs detect both ascending and descending streams. - Constant strides: every 128 bytes, for example. Many cores track a stride per load instruction.
- Adjacent lines: some cores fetch the neighbouring line of a 128-byte pair whenever one line misses.
The exact set of detectors, how far ahead they run, and how many streams they track differ by CPU model. Treat the list above as typical, not guaranteed.
Two ways latency gets hidden
Prefetching is not the only thing that hides memory latency, so it helps to separate two effects.
- Prefetching brings a line in before the load runs.
- Memory-level parallelism (MLP) lets the out-of-order core start several independent loads at once, so their waits overlap.
Both depend on the CPU knowing addresses early. Loads whose addresses depend on earlier loaded data cannot overlap, and a prefetcher cannot predict them unless the addresses happen to be regular.
This gives three levels of access pattern:
| Pattern | Example | Prefetcher helps? | Loads overlap? |
|---|---|---|---|
| Sequential or fixed stride | `a[i]` | Yes | Yes |
| Random but independent addresses | `a[idx[i]]` | No | Yes, up to the core's limit on outstanding misses |
| Dependent chain | `p = p->next` | No | No |
The third row is why a linked list laid out randomly in memory is so slow. Each load must finish before the next address is known, so the full memory latency is paid once per node.
Measuring the three patterns
The program below sums the same number of elements three ways. The pointer-chasing version uses an array of indices that forms one random cycle through all elements, so every step is a dependent load to an unpredictable place.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define N (1u << 24) /* 16M elements; arrays exceed typical cache sizes */
static uint64_t rng_state = 88172645463325252ULL;
static uint64_t rng(void) { /* xorshift64 */
rng_state ^= rng_state << 13;
rng_state ^= rng_state >> 7;
rng_state ^= rng_state << 17;
return rng_state;
}
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);
uint32_t *order = malloc(N * sizeof *order);
uint32_t *next = malloc(N * sizeof *next);
if (!data || !order || !next) return 1;
for (uint32_t i = 0; i < N; i++) { data[i] = 1; order[i] = i; }
/* Fisher-Yates shuffle of the visiting order. */
for (uint32_t i = N - 1; i > 0; i--) {
uint32_t j = (uint32_t)(rng() % (i + 1));
uint32_t tmp = order[i]; order[i] = order[j]; order[j] = tmp;
}
/* Link the shuffled order into a single cycle. */
for (uint32_t i = 0; i < N; i++)
next[order[i]] = order[(i + 1) % N];
double t0 = now();
long s1 = 0;
for (uint32_t i = 0; i < N; i++) s1 += data[i]; /* sequential */
double t1 = now();
long s2 = 0;
for (uint32_t i = 0; i < N; i++) s2 += data[order[i]]; /* independent random */
double t2 = now();
long s3 = 0;
uint32_t p = order[0];
for (uint32_t i = 0; i < N; i++) { s3 += data[p]; p = next[p]; } /* dependent */
double t3 = now();
printf("sequential: %.3f s (sum %ld)\n", t1 - t0, s1);
printf("random: %.3f s (sum %ld)\n", t2 - t1, s2);
printf("chase: %.3f s (sum %ld)\n", t3 - t2, s3);
free(data); free(order); free(next);
return 0;
}Compile with cc -O2 prefetch.c -o prefetch. On typical desktop hardware, expect the random version to be several times slower than sequential, and the chase to be slower still. Printing the sums keeps the compiler from deleting the loops.
Limits of the prefetcher
Hardware prefetchers have constraints that explain several surprising results.
- Page boundaries. Most prefetchers do not cross a 4 KiB page boundary, because the next virtual page may map to an unrelated physical page. Every new page restarts stream detection. Large strides near or above 4 KiB leave the prefetcher with almost nothing to track.
- Training time. A stream needs a few misses before it is recognised. Short runs, such as small arrays or list nodes allocated back to back and traversed for only a few steps, get little benefit.
- Limited tracked streams. A loop that walks many arrays at once, for example 20 separate input streams, can exceed the number of streams the hardware tracks, and some will go unprefetched.
- Bandwidth. Prefetching moves data earlier, not faster. If the loop already saturates memory bandwidth, prefetching cannot help, and wrong guesses waste bandwidth and evict useful lines.
- Irregular strides. Skipping variable-size records of a variable length breaks the stride detector.
A practical consequence: a linked list whose nodes were allocated sequentially from a bump allocator often traverses almost as fast as an array, because the addresses form a regular stream. The same list after many inserts and deletes loses that order. The structure did not change, but the address pattern did.
Software prefetching
When the hardware cannot predict the addresses but you can, you can issue prefetch instructions yourself. GCC and Clang provide __builtin_prefetch(address, rw, locality). The function below applies it to the independent-random case, where addresses come from an index array that is known in advance.
#include <stddef.h>
#include <stdint.h>
#define PF_DIST 16 /* tune per machine; try 8, 16, 32, 64 */
long sum_gather(const int *data, const uint32_t *idx, size_t n) {
long s = 0;
for (size_t i = 0; i < n; i++) {
if (i + PF_DIST < n)
__builtin_prefetch(&data[idx[i + PF_DIST]], 0, 1);
s += data[idx[i]];
}
return s;
}The prefetch distance matters. If it is too short, the line has not arrived when the load runs. If it is too long, the line may be evicted before use. The right value depends on memory latency and on how much work each iteration does, so measure it on the target machine. A prefetch is only a hint, and the CPU may drop it. It cannot help a dependent chain unless you can compute future addresses another way, for example by keeping several independent lists and interleaving their traversal.
Designing for the prefetcher
- Keep hot data in contiguous arrays and visit it in address order.
- Prefer a constant stride to an irregular one, and keep strides well below the page size.
- Do not store the next address inside the data you are loading when an index array or a sorted layout can supply it.
- When you must use pointers, allocate related nodes together, such as from an arena or pool, so that traversal order matches address order.
- Process several independent items at once, for example with batched lookups, so the core can overlap their misses.
Exercise
A loop sums data[idx[i]] over a large array where idx is a random permutation, and it runs much faster than a loop that follows a random linked list over the same number of elements. Explain why, using memory-level parallelism, and say which technique could speed up the first loop.
Show answer
In the permutation loop, every address comes from idx, which is already in memory, so the CPU can issue many loads at once and overlap their misses. In the linked-list loop, each address is only known after the previous load finishes, so each miss is paid in full one after another. The prefetcher helps neither loop, because the addresses are random. The first loop can be sped up with software prefetching (__builtin_prefetch(&data[idx[i + D]])), with the distance D chosen by measurement.