Sub topic 2
Cache lines: how data actually moves
This chapter assumes you know that a CPU cache sits between the core and main memory, and that it is much faster than memory. It also assumes you can read C and do basic binary and hexadecimal arithmetic. Here you will learn what unit of data moves between memory and the cache, how an address maps onto that unit, and what this means for the cost of each access.
The unit of transfer is a line, not a byte
Your code reads individual values: a char, an int, a pointer. The memory system does not. Memory and every cache level exchange data in fixed-size blocks called cache lines. A cache line is a contiguous, aligned chunk of memory, 64 bytes on x86-64 and on most ARM server and desktop chips.
When a load misses the cache, the hardware fetches the whole 64-byte line that contains the requested address and stores it in the cache. The program then gets its few bytes from that copy. The other bytes in the line arrive with no extra request.
This has two consequences:
- Reading one byte costs the same as reading all 64 bytes of its line, once the line is in the cache.
- Reading one byte from each of 64 different lines costs 64 line transfers, even though the program asked for only 64 bytes.
Mapping an address to a line
Lines are aligned. With a 64-byte line, the low 6 bits of an address are the offset inside the line. The remaining high bits identify the line.
#include <stdint.h>
#include <stdio.h>
#define LINE 64u
int main(void) {
uintptr_t addr = 200;
uintptr_t line_start = addr & ~(uintptr_t)(LINE - 1);
uintptr_t offset = addr & (LINE - 1);
printf("address %lu -> line starts at %lu, offset %lu\n",
(unsigned long)addr, (unsigned long)line_start,
(unsigned long)offset);
return 0;
}This prints address 200 -> line starts at 192, offset 8. Addresses 192 through 255 share one line. Address 191 belongs to the previous line, even though it is only 9 bytes away from 200. Distance alone does not tell you whether two values share a line. Alignment matters too.
The table shows how many elements of common sizes fit in one aligned 64-byte line.
| Element | Size in bytes | Elements per line |
|---|---|---|
| `char` | 1 | 64 |
| `int`, `float` | 4 | 16 |
| `double`, pointer (64-bit) | 8 | 8 |
| struct of 24 bytes | 24 | 2 whole elements, with a third straddling the boundary |
| struct of 64 bytes | 64 | 1 |
What a load does
The next diagram follows a single load through a cache.
The check happens on the line, not on the byte. Once the line is in the cache, a later load of any byte in it is a hit. That is the mechanism behind spatial locality, which the next chapter names and develops.
Seeing the line size in a measurement
You can observe the effect directly. The program below allocates 256 MiB of unsigned int and, for each stride, touches every stride-th element. A stride of 1 touches every element. A stride of 16 touches one unsigned int per 64-byte line.
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N ((size_t)64 * 1024 * 1024)
static double now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}
int main(void) {
unsigned int *a = malloc(N * sizeof *a);
if (a == NULL) return 1;
for (size_t i = 0; i < N; i++) a[i] = 1;
for (size_t stride = 1; stride <= 64; stride *= 2) {
double t0 = now();
for (size_t i = 0; i < N; i += stride) a[i] *= 3;
double t1 = now();
printf("stride %2zu (%3zu bytes): %7.1f ms, %9zu accesses\n",
stride, stride * sizeof *a, (t1 - t0) * 1e3, N / stride);
}
unsigned long check = 0;
for (size_t i = 0; i < N; i++) check += a[i];
printf("checksum %lu\n", check);
free(a);
return 0;
}Compile with gcc -O2 stride.c -o stride. The checksum at the end keeps the compiler from deleting the work.
On a typical machine, the time stays roughly flat from stride 1 up to stride 16, even though the number of accesses falls by 16 times. Past stride 16, each access lands in a different line, and the time starts to fall as the number of lines touched falls. The array is far larger than any cache, so the loop is limited by line transfers rather than by arithmetic. Exact numbers depend on your hardware. The flat region and the turning point near 64 bytes are the signature to look for.
Writes move lines too
A store to one byte also works on a whole line. Most caches use a write-allocate, write-back policy:
- On a store miss, the cache first fetches the line, so it can change part of it.
- The store modifies the cached copy, and the line is marked dirty.
- When the line is later evicted, the whole 64 bytes are written back to the next level.
So changing one byte of a cold line costs a line read and, later, a line write. A loop that writes sparsely scattered values moves much more data than the number of stored bytes suggests.
Line size is a property of the machine
Do not hard-code 64 without a reason. Some Apple Silicon chips use 128-byte lines at some levels, and other designs differ. You can ask the system:
getconf LEVEL1_DCACHE_LINESIZE
cat /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_sizeIn C++17, std::hardware_destructive_interference_size in <new> gives the compiler's estimate of a safe separation distance between data used by different threads. Use these as a tuning input. Code that is merely correct must never depend on the line size.
Common mistakes
- Counting bytes instead of lines. "I only read 4 bytes per element" says nothing about cost if each element sits in a different line. Count the distinct lines touched.
- Assuming a struct stays inside one line. A 24-byte struct in an array will sometimes cross a line boundary. A 64-byte struct whose address is not a multiple of 64 always spans two lines.
malloctypically guarantees only 16-byte alignment. If you need line-aligned storage, request it withaligned_alloc(64, size)oralignas(64). - Trusting the first run. The first pass over data pays for loading every line. Time repeated runs after a warm-up, or you will measure the cold start.
- Assuming a small loop is cheap. Ten accesses to ten lines can cost more than a hundred accesses to two lines.
Exercise
An array of 1,000,000 double values starts at a 64-byte-aligned address. A loop reads every element once, in order. How many cache lines does it touch, and how many does it touch if it reads only every 8th element?
Show answer
A double is 8 bytes, so 8 fit in one 64-byte line. Reading all 1,000,000 elements touches 1,000,000 / 8 = 125,000 lines. Reading every 8th element reads 125,000 values, and each one is the first element of a different line, so it touches the same 125,000 lines. The second loop does one eighth of the reads but moves just as much data.
Exercise
A struct is 40 bytes, and an array of them starts at a 64-byte-aligned address. Does element 1 (bytes 40 to 79) fit in one line? What does this suggest about the cost of reading all of that element?
Show answer
No. Element 1 covers bytes 40 to 79, and the first line ends at byte 63, so the element straddles lines 0 and 1. Reading the whole struct needs two lines. Padding the struct to 64 bytes, or reordering and trimming fields to reach 32 bytes, would keep each element inside one line.