Memory Hierarchy (COA Core #4)
A 3.5 GHz core can execute an instruction every 0.29 ns. Main memory takes 60–100 ns to answer. Without a hierarchy, every load would stall the CPU for 200–350 cycles. Caches exist to make the common case look fast, and the arithmetic of hits, misses, and capacity is the core of the subject.
The levels
| Level | Typical size | Latency | Managed by |
|---|---|---|---|
| Registers | 16–32 × 8 bytes | 1 cycle | compiler |
| L1 cache | 32–64 KB, split I/D | 4–5 cycles | hardware |
| L2 cache | 256 KB–1 MB per core | 12–20 cycles | hardware |
| L3 cache | 8–32 MB shared | 30–50 cycles | hardware |
| DRAM | 8–64 GB | 60–100 ns | OS + hardware |
| SSD | 100 GB–4 TB | 50–150 µs | OS |
| HDD | 1–20 TB | 5–10 ms | OS |
SSD and HDD are the secondary storage levels: persistent, block-addressed, and three to six orders of magnitude slower than DRAM.
The pattern: each level is larger and slower by roughly an order of magnitude. The goal is to keep the working set in the fastest level that fits.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
l/.style={draw, thick, minimum height=0.5cm, font=\scriptsize, align=center}]
\node[l, fill=blue!18, minimum width=2.2cm] at (0,0) {registers\\1 cycle};
\node[l, fill=blue!12, minimum width=3.4cm] at (0,-0.6) {L1: 4–5 cycles};
\node[l, fill=blue!8, minimum width=4.6cm] at (0,-1.2) {L2: 12–20 cycles};
\node[l, fill=orange!15, minimum width=5.8cm] at (0,-1.8) {L3: 30–50 cycles};
\node[l, fill=orange!25, minimum width=7.0cm] at (0,-2.4) {DRAM: 60–100 ns};
\node[l, fill=red!15, minimum width=8.2cm] at (0,-3.0) {SSD / HDD: µs–ms};
\node[font=\scriptsize, anchor=west] at (4.3,-0.3) {faster, smaller, costlier per byte};
\end{tikzpicture}
ASolution
SRAM is fast but takes about six transistors per bit and a lot of area. DRAM uses one transistor and a capacitor, so it is dense and cheap but slow. The hierarchy buys speed for the common case at DRAM density for the rest.
Locality of reference
Caches work because programs do not access memory uniformly.
- Temporal locality: an item accessed now is likely to be accessed again soon. Loop counters, hot variables, recently used instructions.
- Spatial locality: items near a recently accessed address are likely to be accessed soon. Array elements, sequential instructions, struct fields.
int sum = 0;
for (int i = 0; i < n; ++i)
sum += a[i]; // spatial: a[i] and a[i+1] share a cache line
// temporal: sum and i stay in registers
A linked list has poor spatial locality: each node is elsewhere in memory, so the next access is a new cache line (and likely a miss). This is why an array traversal can be several times faster than a list traversal at the same Big-O.
ASolution
Mostly temporal for repeated keys, and spatial within a bucket or cache line. A random lookup pattern has poor spatial locality, so large hash tables are memory-latency bound.
Hits, misses, and the four Cs
A hit is serviced by the cache. A miss must fetch from the next level.
\[ \text{hit rate} = \frac{\text{hits}}{\text{accesses}}, \qquad \text{miss rate} = 1 - \text{hit rate} \]
Misses are classified by cause:
| Type | Cause | Fix |
|---|---|---|
| Compulsory (cold) | first access to a block | prefetch, larger blocks |
| Capacity | working set exceeds cache | larger cache, blocking |
| Conflict | too many blocks map to one set | higher associativity |
| Coherence | another core wrote the line | protocol tuning, padding |
A fully associative cache has no conflict misses. A direct-mapped cache has the most. Capacity misses are the ones a bigger cache actually fixes.
category is that?
ASolution
Capacity, because the array is much larger than the cache and each pass evicts data the next pass needs. Conflict misses would also occur in a low-associativity cache, but capacity dominates at this size ratio.
Average Memory Access Time
AMAT combines hit time and miss cost:
\[ \text{AMAT} = t_{\text{hit}} + \text{miss rate} \times t_{\text{miss}} \]
For two levels, the L1 miss penalty is the L2 access:
\[ \text{AMAT} = t_{L1} + m_1\big(t_{L2} + m_2 \cdot t_{\text{mem}}\big) \]
Worked example:
- L1 hit = 1 ns, L1 miss rate = 10%.
- L2 hit = 5 ns, L2 miss rate (of L1 misses) = 50%.
- Memory = 100 ns.
\[ \text{AMAT} = 1 + 0.10\,(5 + 0.50 \times 100) = 1 + 0.10 \times 55 = 6.5 \text{ ns} \]
If L1 hit time were 2 ns instead, AMAT would be 7.5 ns — hit time matters as much as the miss rate when misses are rare.
What is AMAT in cycles?
ASolution
\(1 + 0.05 \times 100 = 6\) cycles. The 5% of misses dominates: the average access is six times the hit time.
Cache lines
A cache line (block) is the unit transferred between levels, typically 64 bytes on
x86 and ARM. A line holds 16 ints or 8 doubles.
Larger lines exploit spatial locality but cost more to transfer and reduce the number of lines for a fixed capacity, which can increase conflict misses. Smaller lines reduce wasted bandwidth on scattered accesses.
The address splits into three fields:
\[ \underbrace{\text{tag}}_{\text{rest}} \;\; \underbrace{\text{index}}_{\log_2(\text{sets})} \;\; \underbrace{\text{offset}}_{\log_2(\text{line size})} \]
The offset selects a byte within the line; the index selects the set; the tag identifies which block occupies the line.
ints fit in a 64-byte cache line?ASolution
16, because each int is 4 bytes and \(64/4 = 16\).
Capacity, associativity, and mapping
\[ \text{capacity} = \text{sets} \times \text{ways} \times \text{line size} \]
- Direct-mapped: one way per set. Each block has exactly one possible line. Fast, simple, prone to conflict misses.
- Set-associative: \(N\) ways per set. A block can go in any of \(N\) lines in its set. Typical: 4–16 ways.
- Fully associative: one set, every line is a candidate. Best hit rate, most expensive to search; used for small structures like TLBs.
Address decomposition on a 32-bit machine with 64-byte lines:
| Cache | Sets | Offset bits | Index bits | Tag bits |
|---|---|---|---|---|
| 32 KB direct (512 lines) | 512 | 6 | 9 | 17 |
| 32 KB 4-way (128 sets) | 128 | 6 | 7 | 19 |
| 32 KB fully associative | 1 | 6 | 0 | 26 |
Higher associativity reduces conflict misses at the cost of more comparators and a more complex replacement policy.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum height=0.5cm, font=\scriptsize\ttfamily}]
\node[c, fill=blue!12, minimum width=2.2cm] (t) at (0,0) {tag (17)};
\node[c, fill=orange!18, minimum width=1.3cm] (i) at (1.75,0) {index (9)};
\node[c, fill=green!15, minimum width=0.9cm] (o) at (2.85,0) {off (6)};
\node[font=\scriptsize, anchor=north] at (2.85,-0.4) {byte in line};
\node[font=\scriptsize, anchor=north] at (1.75,-0.85) {selects the set};
\node[font=\scriptsize, anchor=north] at (0,-1.3) {compared against the stored tag};
\end{tikzpicture}
ASolution
The index determines exactly one line. In an \(N\)-way set, all \(N\) tags in the set must be compared in parallel.
Replacement policies
When a set is full and a new block arrives, one line must go:
- LRU: evict the least recently used. Good hit rate, expensive to track exactly.
- FIFO: evict the oldest. Cheap, can evict a hot line.
- Random: cheap, surprisingly decent, no pathological patterns.
- Pseudo-LRU / clock: an approximation with one reference bit per line, used in real hardware.
Hand simulation, 2-way set, LRU, accesses A B C A:
| Access | Contents | Result |
|---|---|---|
| A | A | miss |
| B | A B | miss |
| C | B C | miss, evict A |
| A | C A | miss, evict B |
With A B A C A: A miss, B miss, A hit, C miss (evict B), A hit → 2 hits.
Direct-mapped, 4 lines indexed by addr mod 4, accesses 0 1 2 3 0 4 0:
| Access | Index | Result |
|---|---|---|
| 0 | 0 | miss |
| 1 | 1 | miss |
| 2 | 2 | miss |
| 3 | 3 | miss |
| 0 | 0 | hit |
| 4 | 0 | miss, evicts 0 |
| 0 | 0 | miss |
One hit out of seven. The 0,4,0 pattern is a conflict miss: both blocks map to set
0.
ASolution
LRU assumes recency predicts the future. A cyclic scan larger than the cache makes every line “least recently used” just before it is needed again, so LRU evicts exactly what the next access wants.
Write policies
Two independent decisions:
When to write to the next level:
- Write-through: every write goes to memory as well as the cache. Simple, keeps memory current, but generates traffic.
- Write-back: write only the cache; mark the line dirty; write it back on eviction. Less traffic, more complexity, needs a dirty bit.
What to do on a write miss:
- Write-allocate: load the line into the cache, then modify it. Good for repeated writes to the same line.
- No-write-allocate: write straight to memory, do not cache. Pairs with write-through.
| Combination | Behaviour | Typical use |
|---|---|---|
| Write-back + write-allocate | cache it, dirty it, flush later | L1/L2/L3 on CPUs |
| Write-through + no-write-allocate | memory always current | simple caches, some GPUs |
| Write-through + write-allocate | cache it and write memory | rare |
Dirty lines complicate coherence: another core reading the line must get the modified data, not stale memory. That is the job of the coherence protocol (Ch. 6).
ASolution
Multiple writes to the same line collapse into one writeback when the line is evicted, instead of one memory write per store.
Worked cache problem
A 16 KB direct-mapped cache with 32-byte lines, 32-bit addresses:
- Lines: \(16384 / 32 = 512\).
- Offset bits: \(\log_2 32 = 5\).
- Index bits: \(\log_2 512 = 9\).
- Tag bits: \(32 - 5 - 9 = 18\).
The address 0x12345678 splits as:
- offset =
0x78 & 0x1F=0x18(24), - index =
(0x12345678 >> 5) & 0x1FF=0x2B3 & 0x1FF=0xB3(179), - tag =
0x12345678 >> 14=0x48D1.
Two addresses map to the same set if their index bits match; they hit only if the tags also match.
conflict?
ASolution
Yes. They have the same index but different tags, so they map to the same line and evict each other on alternating accesses.
Bugs and edge cases
- Assuming a bigger cache always helps. A larger cache can have the same associativity and more conflict misses for a stride-based pattern.
- Ignoring line size. Two arrays that share a line (false sharing) or a stride that is a multiple of the line size (worst case) behave very differently.
- Confusing hit rate with speed. A 99% hit rate with a 500-cycle miss penalty is still slow.
- Forgetting writebacks. Dirty data must be flushed before the line is reused; benchmarks often overstate gains by ignoring this.
- Comparing AMAT across different clock speeds. Cycles and nanoseconds are different units.
- Assuming LRU is used everywhere. Many real caches use pseudo-LRU or random.
cache with 64-byte lines. Why?
ASolution
4096 bytes is 64 lines; with 64 sets, the stride maps every access to the same set. Eight ways fill and then evict each other — a conflict miss pattern, not a capacity problem.
Next: TLB and Virtual Memory Hardware (COA Core #5) — translating addresses at speed, and simulating an LRU TLB by hand.