Textbooks/Computer Architecture/Chapter 4Lite (plain text) version
4Caches and the memory hierarchy
Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items
Introduction
Main memory is a hundred times slower than the processor, so every modern chip hides it behind caches that bet on locality: what you used recently, and what sits next to it, you will probably use again. This chapter opens a cache: how an address splits into tag, index and offset, what associativity buys, how average memory access time folds misses into one number, and how ablation shows which cache change really helped.
Explanation
This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
4.1 Locality and the memory hierarchy
Two loops add up the same million numbers. One is ten times slower. Same chip, same maths. What is different?
The hierarchy
Registers (bytes to a few KB, under a nanosecond), L1 cache (tens of KB, about 1 ns), L2/L3 (hundreds of KB to tens of MB, several to tens of ns), DRAM (GB, around 100 ns), flash or disk (TB, microseconds to milliseconds). Each level is bigger, slower and cheaper per byte than the one above. Typical figures vary widely between chips.
Temporal locality
Data used now is likely to be used again soon: loop counters, a filter's coefficients, the top of the stack. Keeping recently used data in a small fast memory serves those repeat visits.
Spatial locality
Data near what you just used is likely to be used next: the next array element, the next instruction. Caches move whole blocks (often 64 bytes) so one miss pre-loads the neighbours. Walking a 2-D array row by row in a row-major language uses this; walking it column by column wastes it.
Common mix-ups
- Memory access time is constant, so only operation counts matter.
✓ A cache miss can cost 100 times a hit. Access patterns change real run time massively. - Bigger blocks are always better.
✓ They help sequential access but waste bandwidth and capacity on strided or random access.
4.2 Inside a cache: tags, sets and ways
A cache holds a tiny fraction of memory. When the CPU asks for address 0x1F40, how does the cache know in one nanosecond whether it has it?
Offset, index, tag
With B-byte blocks, the lowest log₂ B bits are the offset (which byte in the block). With S sets, the next log₂ S bits are the index (which set to look in). The remaining high bits are the tag, stored with the block and compared on every access. Sets S = cache size ÷ (block size × ways).
Direct-mapped versus set-associative
Direct-mapped (1 way): each block has exactly one possible line. Fast and simple: one tag comparison. N-way set-associative: each set holds N blocks, so N comparisons happen in parallel and a multiplexer picks the hit way. Conflict misses fall; area, energy and sometimes hit time rise. Fully associative is one set holding everything.
Replacement and writes
When a set is full, LRU (least recently used) evicts the block untouched for longest; real caches often approximate it. Stores need a policy too: write-through sends every write to the next level; write-back marks the block dirty and writes it only on eviction, saving bandwidth.
The hardware cost
Each way needs a tag-width equality comparator: one XNOR per bit plus an AND tree, and a valid bit. A 4-way cache with 18-bit tags needs 4 × 18 = 72 XNORs before the AND trees and way multiplexer. That is the area and energy behind 'just add associativity'.
Common mix-ups
- Higher associativity always makes a cache better.
✓ It cuts conflict misses but adds comparators, energy and sometimes hit time. Gains shrink beyond 8 ways for many workloads. - The index bits are the high bits of the address.
✓ Index comes just above the offset, so consecutive blocks fall in consecutive sets.
4.3 Average memory access time
A cache hits 95% of the time. Is that good? It depends entirely on what the other 5% cost.
One formula, three levers
AMAT = hit time + miss rate × miss penalty. Reduce hit time (small, simple L1), reduce miss rate (bigger, more associative, better prefetching) or reduce miss penalty (an L2, faster memory, critical-word-first). They fight: bigger and more associative usually means slower hits.
Local and global miss rates
L2's local miss rate looks bad (20–50% is common) because L1 has already filtered out the easy accesses. What matters for AMAT is the global rate m₁·m₂, often well under 1%.
Back to the Iron Law
Memory stalls add to CPI. A program with 0.3 memory accesses per instruction and 1.5 extra cycles per access from misses gains 0.45 CPI: as much as many branch-prediction improvements. This is why memory is often called the bottleneck.
Derivation: AMAT for two levels, and back into CPI
One level: every access pays h₁; a fraction m₁ also pays the penalty P₁. AMAT = h₁ + m₁P₁.
With L2, an L1 miss is served by L2, whose own average time is h₂ + m₂·t_mem, where m₂ is L2's local miss rate (misses ÷ accesses that reach L2).
So P₁ = h₂ + m₂·t_mem and AMAT = h₁ + m₁(h₂ + m₂·t_mem).
Global L2 miss rate = m₁·m₂: the fraction of all accesses that reach memory.
Memory stall cycles per instruction = (memory accesses per instruction) × (AMAT − h₁), if the hit time is already counted in base CPI.
Example: h₁ = 1, m₁ = 0.05, h₂ = 10, m₂ = 0.2, t_mem = 100: AMAT = 1 + 0.05 × 30 = 2.5 cycles, versus 6 without L2.
Common mix-ups
- A 95% hit rate means memory is 95% as fast as the cache.
✓ With a 100-cycle penalty, AMAT is 6× the hit time. Misses dominate. - A 30% L2 miss rate means L2 is useless.
✓ It is a local rate on the hard accesses L1 missed; the global rate is far lower.
4.4 Ablations: which part made it better?
Your new design is 40% faster. It has a bigger cache, a new predictor and a compiler flag. Which one did the work?
One change at a time
Start from the full system and remove (or start from the baseline and add) one component per run, holding everything else fixed: same inputs, same metric, same conditions. The difference from the reference attributes performance to that component.
Interactions
Components can interact: a bigger cache may make a prefetcher less useful, or a predictor may matter only with a deep pipeline. A full factorial design (every combination; 2ⁿ runs for n on/off components) reveals interactions; with many components, test the most plausible pairs.
Explain, don't just tabulate
Tie each effect to a mechanism. 'Two-way associativity removed the conflict misses because a[i] and b[i] share index bits' is a finding; '2-way is 4× better' is only a number. Mechanism-level explanations generalise to new workloads; raw numbers may not.
Common mix-ups
- If the full system is better, every component must be helping.
✓ Some may do nothing or even hurt; only ablations show it. - Ablating each component once is enough.
✓ Components can interact; check plausible combinations and report uncertainty on each effect.
Open the full lesson: Ablations: which part made it better? →
Worked examples
Locality and the memory hierarchy: example 1
A C program sums a 1000×1000 int matrix as sum += a[j][i] (column by column). Why is it slow, and what is the fix?
Solution
C stores rows contiguously, so a[j][i] then a[j+1][i] are 4000 bytes apart: every access touches a new block. Swap the loops to a[i][j] so consecutive accesses share blocks; the miss rate drops from about 100% to about 4/64 ≈ 6%.
Inside a cache: tags, sets and ways: example 1
A 32 KB direct-mapped cache, 64 B blocks, 32-bit addresses. Split the address.
Solution
Offset = log₂ 64 = 6. Sets = 32768/64 = 512, index = 9. Tag = 32 − 9 − 6 = 17 bits.
Inside a cache: tags, sets and ways: example 2
Same cache made 2-way. What changes?
Solution
Sets halve to 256, so index = 8 and tag = 18. Two 18-bit comparators run in parallel per access.
Average memory access time: example 1
Option A: 1-cycle L1, 6% miss rate. Option B: 2-cycle L1, 3% miss rate. Both backed by a 40-cycle L2 that never misses. Which is better?
Solution
A: 1 + 0.06×40 = 3.4. B: 2 + 0.03×40 = 3.2. B wins slightly; with a 30-cycle L2 they tie at 2.8 and 2.9 (A wins). The answer depends on the penalty.
Ablations: which part made it better?: example 1
Simulator misses for the colliding arrays: baseline (direct-mapped, 16 B) 16; 2-way only 4; 32 B blocks only 2; both 2. Main effects and interaction?
Solution
Associativity: ½[(4 − 16) + (2 − 2)] = −6. Block size: ½[(2 − 16) + (2 − 4)] = −8. Interaction: ½[(2 − 2) − (4 − 16)] = +6: once one fix removes the conflict, the other adds nothing. Mechanism: with 8 lines fixed, 32 B blocks double the cache to 256 B, so a[i] and b[i] no longer share an index. A cleaner ablation holds capacity fixed (halve the lines when doubling the block).
Interactive figures
Interactive figure (online). Description: The cache simulator lists each address, its set and tag, and whether it hits. With 16-byte blocks: walking 32 integers gives 8 misses and 24 hits; reading 16 integers twice gives 4 misses; a 64-byte stride misses every time.
Interactive figure (online). Description: The AMAT explorer shows a stacked bar: L1 hit time, plus L1 misses times L2 time, plus global misses times memory time. With h₁ = 1, m₁ = 5%, h₂ = 10, m₂ = 20% and memory 100 cycles, AMAT = 2.5 cycles; without L2 it is 6.
Laboratory
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Simulation OS experiment
Simulation OS: Cache hit rate
Sweep the stride of an array walk and the associativity, and find the stride where a direct-mapped cache collapses.
Open Simulation OS: Cache hit rate →Silicon Studio stage
Silicon Studio: Memory
Read and write words at chosen addresses and identify which address bits select the row.
Open Silicon Studio: Memory →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?
- Temporal
- Spatial only
- Neither
- Only compulsory misses
- Reading every 64th byte with 16-byte blocks gives 100% misses. What happens if blocks grow to 32 bytes?
- Misses halve
- Still 100% misses
- No misses
- Misses double
- Going from direct-mapped to 4-way set-associative at the same capacity mainly costs…
- More tag comparators and a way multiplexer
- More capacity
- Smaller blocks
- Nothing: it is free
- A single set with 2 ways and LRU replacement sees blocks A, B, A, C, B. Which accesses hit?
- Only the second A
- The second A and the last B
- None
- All after the first two
- L1 miss rate is 4% and L2 local miss rate is 25%. What percentage of all accesses go to main memory? (%)
- AMAT = 1 + 0.08 × 50. Which single change helps most?
- Cut hit time from 1 to 0.5 cycles
- Cut miss rate from 8% to 6%
- Cut miss penalty from 50 to 45 cycles
- All save the same
- Base CPI is 1. There are 0.4 memory accesses per instruction, L1 hit time is included in base CPI, and AMAT is 3 cycles with a 1-cycle hit time. What is the effective CPI?
- A 2×2 study of predictor (P) and cache (C) gives run times (ms): neither 100, P only 80, C only 70, both 55. What is the main effect of P (ms)? (ms)
Engineering applications
Data layout
Storing particles as separate arrays of x, y and z, rather than an array of records, can make a loop that reads only x touch a third as many cache blocks.
Real-time timing
A cache miss in the middle of a control loop can add microseconds. Safety-critical controllers lock their code into cache or tightly coupled memory so the worst case is known.
Watch
Optional verified videos. Nothing loads from YouTube until you press play.
- Why do CPUs Need Caches? - Computerphile (Computerphile)
- How CPU Memory & Caches Work - Computerphile (Computerphile)
- Memory & Storage: Crash Course Computer Science #19 (CrashCourse)
Chapter summary
- Temporal and spatial locality are why caches work; access patterns decide hit rates.
- Address = tag | index | offset: offset bits from the block size, index bits from the number of sets.
- Associativity reduces conflict misses at the cost of more comparators and power.
- AMAT = hit time + miss rate × miss penalty, applied level by level.
- An ablation changes one cache feature at a time to show which one caused the gain.
Glossary
- Memory hierarchy and caches
- Computers use a hierarchy of memories from tiny fast registers and caches to large slow main memory and storage; a cache keeps recently used data close to the processor.
- Average memory access time (AMAT)
- Average memory access time is the cache hit time plus the miss rate multiplied by the miss penalty.
- Address space
- The address space is the range of addresses a processor can generate. With n address bits and byte addressing, it can reach 2^n bytes.
- RAM, flash and EEPROM
- RAM is fast, volatile working memory that loses its contents without power; flash and EEPROM are non-volatile and keep data, but are slower to write and wear out after many write cycles.
Definitions from the Field Guide.
Project: Size a cache for a known workload
Choose a loop that walks an image or a sensor log. Predict its hit rate for two cache sizes and two associativities, check with the cache simulation, and compute AMAT for each. Recommend one configuration with its area cost in mind.
Deliverables
- Predicted and simulated hit rates in a table
- AMAT for each configuration
- A recommendation weighing speed against area
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
References
- Alan Jay Smith (1982). "Cache Memories". ACM Computing Surveys 14(3), 473–530.
- Wm. A. Wulf and Sally A. McKee (1995). "Hitting the Memory Wall: Implications of the Obvious". ACM SIGARCH Computer Architecture News 23(1), 20–24. doi:10.1145/216585.216588 Link ↗
- John L. Hennessy and David A. Patterson (2017). Computer Architecture: A Quantitative Approach, 6th edition. Morgan Kaufmann.
- Randal E. Bryant and David R. O'Hallaron (2016). Computer Systems: A Programmer's Perspective, 3rd edition. Pearson.
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.