Sub topic 2
Cache lines: how data actually moves
This chapter assumes you know C or a similar language, how arrays and structs sit in memory, and the memory hierarchy from the previous chapter (registers, L1, L2, L3, main memory).
The cache moves blocks, not bytes
When your program reads one int, the CPU does not fetch four bytes from memory. It fetches a whole cache line, a fixed-size aligned block of memory. On x86-64 and most current ARM cores, a line is 64 bytes. Some designs use 128 bytes, so treat 64 as common and not guaranteed.
Aligned means the line starts at an address divisible by the line size. Memory is divided into consecutive 64-byte lines, and every byte belongs to exactly one of them.
The first access pays the full memory latency, often around 100 ns. The next 15 int reads in that line cost a few cycles each. That difference is why layout matters.
Seeing the lines
This program prints the line number of each int in an array aligned to 64 bytes.
#include <stdio.h>
#include <stdint.h>
_Alignas(64) static int a[32];
int main(void) {
for (int i = 0; i < 32; i += 4) {
uintptr_t line = (uintptr_t)&a[i] / 64;
printf("a[%2d] -> line offset %ju\n", i, (uintmax_t)(line - (uintptr_t)a / 64));
}
return 0;
}It prints offsets 0, 0, 0, 0, 1, 1, 1, 1. Sixteen consecutive int values share one line, so reading all 32 elements costs two line transfers, not 32.
Consequences
- Sequential access is cheap. One miss pays for the next 15
intreads, or 7doublereads. - Unused bytes are wasted bandwidth. If you read one 4-byte field from a 64-byte struct, you still move 64 bytes.
- Straddling costs double. An object that crosses a line boundary needs two lines.
- Writes work on lines too. Writing one byte makes the core take ownership of the entire line. This matters for the false sharing chapter.
A rough cost model is the number of distinct lines touched, not the number of bytes or instructions.
Exercise
A loop reads every 16th element of a large int array (stride of 64 bytes) and a second loop reads every element. Both start cold. Which loop touches more cache lines, and why might they run in a similar time?
Show answer
Both touch the same number of lines. The strided loop reads one int per line, so it still touches every line. The sequential loop reads all 16 int values in each line. Since line transfers dominate the cost, the two loops can take similar time even though the strided one does 16 times fewer reads.