← All lessons
How a CPU cache works
Look up one int
CPU
L1
L2
L3
RAM
read.c
int *a = data; // say it lives at 0x00601C48int x = a[0]; // miss, about 97 nsint y = a[1]; // same line: hitl1.c
// what L1 does with every loaduint32_t offset = addr & 63;uint32_t set = (addr >> 6) & 63;uint32_t tag = addr >> 12;for (int w = 0; w < 8; w++) if (l1[set][w].tag == tag) return l1[set][w].data[offset]; // hit, about 1 nsline = next_level(addr); // L2, then L3, then RAMw = least_recently_used(l1[set]);l1[set][w] = line; // evicts the old linereturn line.data[offset];Grow the data until it falls out of each cache
Where the reads were answered
L132 KB per core · 1 ns
L21 MB per core · 4 ns
L38 MB, shared · 12 ns
RAM16 GB, off the chip · 80 ns
per read, on average
chase.c
// one read per line, in a random cyclefor (size_t i = 0; i < lines; i++) next[order[i]] = order[(i + 1) % lines]; size_t p = order[0];for (long k = 0; k < reads; k++) p = next[p]; // each read waits for the one before // up to 32 KB: L1, about 1 ns// up to 1 MB: L2, about 4 ns// up to 8 MB: L3, about 12 ns// bigger: RAM, about 80 nsRows or columns same sum, very different speed
Top-left corner, colored by who answered each read
reads
L1 hits
avg
total
Real CPUs also prefetch the next lines in a row walk, so rows get even faster than this
sum.c
int m[N][N]; // stored row by row: m[i][0], m[i][1], … sit side by sidelong sum = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) sum += m[i][j]; // the next int, usually the same line for (int j = 0; j < N; j++) for (int i = 0; i < N; i++) sum += m[i][j]; // N × 4 bytes away, a new line every timeTopics
Next: How context switching works
Open lesson