Why a hierarchy
DRAM is large but a hundred times slower than the core; SRAM is fast but small and expensive. Caches exploit the fact that programs reuse recently used data (temporal locality) and use data near what they just used (spatial locality). A typical recent server core:
| Level | Typical size | Shared by |
|---|---|---|
| L1 data and L1 instruction | 32–64 KiB each | one core |
| L2 | 256 KiB – 2 MiB | one core |
| L3 (last-level cache) | tens of MiB | all cores on a socket (or a chiplet) |
| DRAM | GiB to TiB | the socket, or remote across NUMA |
Each level is slower and larger than the one before. The latency of each level is in the Systems and Low-Latency Basics lesson; here the focus is how caches are organised and how code interacts with them.
Lines, sets and ways
Caches store fixed-size lines: 64 bytes on x86-64 (Apple silicon reports 128). Any access brings in the whole line containing it.
A cache with sets of lines each is -way set associative. An address is split into three fields:
The index chooses the set; the line may sit in any of that set's ways, found by comparing tags. When the set is full, one line is evicted (approximately least recently used).
- Direct mapped (): cheap and fast, but two hot addresses with the same index evict each other forever.
- Fully associative (): no such conflicts, but every lookup compares every tag; used for small structures such as TLBs.
- Real data caches are in between: 8 to 16 ways is common.
For a 32 KiB, 8-way L1 with 64-byte lines: sets, so bits 0–5 are the offset and bits 6–11 the set index. The set index repeats every bytes, so addresses exactly 4 KiB apart land in the same set, and at most 8 of them fit at once.
The three Cs of misses
- Compulsory: first access to a line. Reduced only by prefetching or by touching less data.
- Capacity: the working set is larger than the cache. Reduced by shrinking or blocking the working set.
- Conflict: the cache has room, but too many hot lines map to one set. Typical cause: power-of-two strides. Reduced by padding or changing the layout.
In multicore systems add coherence misses: a line written by another core must be re-fetched. False sharing, covered in Systems and Low-Latency Basics, is this effect on unrelated data.
Caches are write-back and write-allocate: a store brings the line in, modifies it, and the line is written to the next level only when evicted.
Prefetching and memory-level parallelism
Hardware prefetchers watch the stream of misses and fetch lines ahead of time. They handle sequential and constant-stride access well, usually within a 4 KiB page. They cannot help when the next address depends on the data just loaded (pointer chasing).
Independent misses also overlap: a core can have on the order of ten or more outstanding L1 misses at once. A loop over an array with independent iterations keeps many misses in flight, so its throughput is set by bandwidth rather than latency. A linked-list walk has one miss in flight at a time and pays the full latency for every node.
Average memory access time
applied recursively: the L1 miss penalty is itself the AMAT of L2. Because the miss term is multiplied by the latency of a much slower level, a small change in the miss rate can matter more than a large change in hit time.
Worked example
average memory access time
An L1 hit takes 4 cycles and 5% of accesses miss L1. An L2 hit takes 12 cycles and 20% of the accesses that reach L2 miss it. Memory takes 200 cycles (ignore L3). Find the AMAT. What does it become if a better layout halves the L1 miss rate?
Show solutionHide solution
L2's AMAT is cycles. That is the L1 miss penalty, so
With the L1 miss rate at 2.5%: cycles, about 20% faster overall, from a change that touches only 2.5% of accesses. Equivalently, of the 6.6 cycles, only 4 are L1 hits and 2.6 come from the 5% that miss. Interviewers like this framing: the rare slow case dominates.
A stride benchmark
This program walks a 64 MiB array (far larger than any cache) touching every stride-th int, and reports total time and time per touch:
#include <chrono>
#include <cstdio>
#include <vector>
int main() {
std::vector<int> a(64 * 1024 * 1024 / sizeof(int), 1); // 64 MiB
for (size_t stride : {1, 2, 4, 8, 16, 32, 64, 128, 256}) {
auto t0 = std::chrono::steady_clock::now();
for (int rep = 0; rep < 5; ++rep)
for (size_t i = 0; i < a.size(); i += stride) a[i] *= 3;
auto t1 = std::chrono::steady_clock::now();
double ms = std::chrono::duration<double, std::milli>(t1 - t0).count() / 5;
double touches = double(a.size()) / stride;
std::printf("stride %3zu ints (%4zu B): %6.2f ms, %6.2f ns per touch\n",
stride, stride * sizeof(int), ms, ms * 1e6 / touches);
}
std::printf("%d\n", a[0]); // keep the work observable
}
The shape of the result, not the exact numbers, is what to remember:
- Strides up to the line size: every line is still fetched, so memory traffic is the same and total time stays roughly flat even though the number of touches falls by up to 16 times. Time per touch rises in proportion to the stride. (At stride 1 the loop may be limited by instruction throughput rather than memory, so it can be somewhat slower.)
- Strides beyond the line size: each doubling halves the number of lines fetched, so total time roughly halves, while time per touch levels off at the cost of one line fetch that the prefetcher partly hides, several nanoseconds.
- The knee in the curve sits at the cache-line size: 64 bytes on x86-64; on an Apple-silicon laptop (128-byte lines) the flat region extends to 128 bytes.
Variants of the same idea measure cache sizes (time per access jumps when the array outgrows L1, L2, L3) and latency versus bandwidth (random pointer chasing versus streaming).
Worked example
row order versus column order
A 4096 × 4096 matrix of 4-byte ints is stored row-major (64 MiB). Compare summing it row by row with summing it column by column. Count L1 line fetches, and explain why column order is worse than capacity alone suggests, using a 32 KiB, 8-way, 64-byte-line L1 and a 1 MiB, 16-way L2.
for (size_t i = 0; i < N; ++i)
for (size_t j = 0; j < N; ++j) s1 += m[i * N + j]; // row order
for (size_t j = 0; j < N; ++j)
for (size_t i = 0; i < N; ++i) s2 += m[i * N + j]; // column order
Show solutionHide solution
Row order reads consecutive addresses. A 64-byte line holds 16 ints, so there are line fetches, all sequential, and the prefetcher streams them.
Column order jumps one row, bytes, per step. Each access is to a different line. Would the 16 columns that share each line be served from cache? Only if the cache held one line from every row, that is 4,096 lines or 256 KiB, until the next column comes round. It cannot:
- Capacity: 256 KiB is 8 times the L1.
- Conflict: the L1 set index repeats every 4 KiB and the stride is 16 KiB, a multiple of 4 KiB, so every element of a column maps to the same L1 set. Only 8 of the 4,096 lines can be resident. In the L2 (1,024 sets of 64-byte lines, so the index repeats every 64 KiB), a 16 KiB stride cycles through just 4 sets, lines, also far short of 4,096.
So column order misses on essentially every access: about L1 fetches, 16 times as many as row order, and the jumps cross a page every step, defeating the prefetcher and the small-page TLB as well.
Measured on an Apple-silicon laptop with -O2, the column loop was 14 to 29 times slower across runs (about 4–6 ms against 90–108 ms). Expect an order of magnitude on any machine. Fixes: loop in storage order, transpose once, or block the loops into tiles that fit in L1. Padding each row by one cache line breaks the set conflicts.
Knowledge check
A 48 KiB, 12-way set-associative cache has 64-byte lines. How many sets does it have, and how many address bits select the set?
Knowledge check
In the stride benchmark over a 64 MiB array on x86-64, why does total time stay roughly flat for strides of 4, 8 and 16 ints?
Knowledge check
A loop touches nine arrays at the same index, and each array starts at an address that is a multiple of 64 KiB. The loop is much slower than its data volume suggests, even though the arrays together are tiny per iteration. What kind of miss is this, and what is the fix?
Key takeaways
- Caches move 64-byte lines (128 on Apple silicon) and are set associative: index bits choose a set, tags choose a way.
- Misses are compulsory, capacity, conflict or coherence. Power-of-two strides cause conflict misses.
- Prefetchers and overlapping misses make sequential, independent access fast; dependent pointer chasing pays full latency.
- AMAT , applied level by level: the rare miss dominates.
- Cost tracks lines moved, not elements touched. Traverse in storage order, block into tiles, and pad to break conflicts.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).