Skip to content
Tactiverge

Textbooks/Digital Logic and Computer Architecture/Chapter 9

9The memory hierarchy

Version 1 · Technically checked (automated checks only) · 3 source lessons · 7 practice items

Text
All chapters and search
  1. 1. Information as bits
  2. 2. Logic gates and Boolean algebra
  3. 3. Combinational building blocks
  4. 4. Binary arithmetic
  5. 5. From silicon to switches
  6. 6. State machines and sequential logic
  7. 7. Instructions and the datapath
  8. 8. Performance and pipelining
  9. 9. The memory hierarchy
  10. 10. Power, performance and the chip

Introduction

A processor can work far faster than main memory can supply data. Caches close the gap by keeping recently and nearby used data in small, fast storage close to the processor. This chapter explains why programs show locality, how an address is split into tag, index and offset, and how to measure the result with the average memory access time.

RegistersL1 cacheL2 cacheMain memoryStoragefasterlargerAMAT = hit time + miss rate × miss penalty= 1 + 0.05 × 100 = 6 cycles
Figure 9.1. The memory hierarchy and AMAT. A stack of levels from top to bottom: registers, L1 cache, L2 cache, main memory, storage. An arrow on one side says smaller and faster towards the top; an arrow on the other says larger and slower towards the bottom. Below: AMAT = hit time + miss rate × miss penalty, for example 1 + 0.05 × 100 = 6 cycles.

Explanation

This chapter is built from 3 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.

9.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.

Open the full lesson: Locality and the memory hierarchy →

9.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.

Open the full lesson: Inside a cache: tags, sets and ways →

9.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
  1. One level: every access pays h₁; a fraction m₁ also pays the penalty P₁. AMAT = h₁ + m₁P₁.

  2. 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).

  3. So P₁ = h₂ + m₂·t_mem and AMAT = h₁ + m₁(h₂ + m₂·t_mem).

  4. Global L2 miss rate = m₁·m₂: the fraction of all accesses that reach memory.

  5. Memory stall cycles per instruction = (memory accesses per instruction) × (AMAT − h₁), if the hit time is already counted in base CPI.

  6. 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.

Open the full lesson: Average memory access time →

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.

Interactive figures

Figure 9.2 from Locality and the memory hierarchyRun 'Walk an array', then 'Small loop, twice', then 'Big stride', all direct-mapped with 16 B blocks. For each, predict the hit rate before you press Show all. Then try 32 B blocks on the array walk and on the stride.
Can't use the interactive? Read a description instead

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 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.

Figure 9.3 from Average memory access timeStart with L2 off. Raise main-memory latency and watch AMAT climb. Turn L2 on and find the L2 miss rate at which it stops being worth having. Which change saves more: halving the L1 miss rate, or halving the L2 hit time?
Can't use the interactive? Read a description instead

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.

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

    Change the cache size and the access pattern, and explain why a large stride hurts the hit rate.

    Open Simulation OS: Cache hit rate →
  • Silicon Studio stage

    Silicon Studio: Memory

    Store and load values at several addresses, and note which address bits select the word.

    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.

Practice 1

A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?

Practice 2

A loop reads 256 consecutive 4-byte floats into an empty cache with 64-byte blocks. How many misses?

misses

Practice 3 · a fresh version every time

A 32 KB 4-way set-associative cache has 16-byte blocks and 64-bit byte addresses. How many offset bits are there?

bits

Practice 4

How many single-bit XNOR gates do the tag comparators of an 8-way cache with 20-bit tags need?

XNORs

Practice 5 · a fresh version every time

A cache has a hit time of 3 cycles, a miss rate of 1% and a miss penalty of 100 cycles. What is the AMAT in cycles?

cycles

Practice 6

L1 miss rate is 4% and L2 local miss rate is 25%. What percentage of all accesses go to main memory?

%

Practice 7

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?

  1. A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?
    • Temporal
    • Spatial only
    • Neither
    • Only compulsory misses
  2. A loop reads 256 consecutive 4-byte floats into an empty cache with 64-byte blocks. How many misses? (misses)
  3. A 32 KB 4-way set-associative cache has 16-byte blocks and 64-bit byte addresses. How many offset bits are there? (bits)
  4. How many single-bit XNOR gates do the tag comparators of an 8-way cache with 20-bit tags need? (XNORs)
  5. A cache has a hit time of 3 cycles, a miss rate of 1% and a miss penalty of 100 cycles. What is the AMAT in cycles? (cycles)
  6. L1 miss rate is 4% and L2 local miss rate is 25%. What percentage of all accesses go to main memory? (%)
  7. 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?

Engineering applications

  • Faster image processing

    Looping over an image row by row reads neighbouring bytes, so each cache block fetched is fully used. Looping column by column can touch a new block on almost every read and run much slower on the same data.

  • Embedded memory budgets

    Small microcontrollers may have no data cache at all, so their designers place time-critical data in on-chip memory instead. Knowing the hierarchy tells you where each variable should live.

Watch

Optional verified videos. Nothing loads from YouTube until you press play.

A history of memory technologies that makes the speed-versus-capacity trade-off of the hierarchy concrete.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

  • Memory & Storage: Crash Course Computer Science #19 (CrashCourse)

Chapter summary

  • Temporal locality: recently used data is likely to be used again soon. Spatial locality: nearby data is likely to be used soon.
  • Each level of the hierarchy is smaller and faster than the one below it.
  • A cache splits an address into tag, index and offset; associativity trades extra comparators for fewer conflict misses.
  • AMAT = hit time + miss rate × miss penalty, applied level by level.

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.
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.
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.

Definitions from the Field Guide.

Project: Size a cache for a sensor log

A controller reads a 4 KiB log sequentially, again and again. Compare a 1 KiB and an 8 KiB cache with 16-byte blocks: estimate the miss rate of each on repeated passes and the AMAT with a 1-cycle hit time and a 50-cycle miss penalty. Explain the difference using locality.

Deliverables

  • Miss-rate estimates for both caches with reasoning
  • AMAT for both
  • A one-paragraph recommendation

Keep your work in your Engineering Journal; it stays private unless you choose to share it.

References

  • John L. Hennessy and David A. Patterson (2017). Computer Architecture: A Quantitative Approach, 6th edition. Morgan Kaufmann.
  • 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 ↗

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.