TactivergeLite

Lite / Textbooks / Computer Architecture / Chapter 4

4. Caches and the memory hierarchy

Version 1 · Technically checked (automated checks only) · 4 source lessons · Full interactive version

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.

Figure 4.1. Splitting an address (described in words)

A 32-bit address for a 4 KiB, two-way set-associative cache with 64-byte blocks. The offset takes 6 bits, there are 32 sets so the index takes 5 bits, and the remaining 21 bits form the tag compared in each way.

Explanation

Built from 4 School lessons. Each part is the lesson's own explanation.

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

Open the Lite lesson: Locality and the memory hierarchy

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

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

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

Open the Lite lesson: Average memory access time

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

Open the Lite 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, in words

Figure 4.2 from Locality and the memory hierarchy

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

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 4.3 from Average memory access time

Start 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?

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.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?
    Answer it in “Locality and the memory hierarchy”
  2. Reading every 64th byte with 16-byte blocks gives 100% misses. What happens if blocks grow to 32 bytes?
    Answer it in “Locality and the memory hierarchy”
  3. Going from direct-mapped to 4-way set-associative at the same capacity mainly costs…
    Answer it in “Inside a cache: tags, sets and ways”
  4. A single set with 2 ways and LRU replacement sees blocks A, B, A, C, B. Which accesses hit?
    Answer it in “Inside a cache: tags, sets and ways”
  5. L1 miss rate is 4% and L2 local miss rate is 25%. What percentage of all accesses go to main memory?
    Answer it in “Average memory access time”
  6. AMAT = 1 + 0.08 × 50. Which single change helps most?
    Answer it in “Average memory access time”
  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?
    Answer it in “Average memory access time”
  8. 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)?
    Answer it in “Ablations: which part made it better?”

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)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

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. Field Guide
Average memory access time (AMAT)
Average memory access time is the cache hit time plus the miss rate multiplied by the miss penalty. Field Guide
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. Field Guide
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. 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

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 3. Pipelining and hazards5. Input, output and the hardware–software boundary →