Lecture 9 · The memory hierarchy

Introduction to Computer Systems · Lecture 09。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 9 (Sep 22), slide deck 09-memory-hierarchy. Reading: CS:APP3e §6.1–6.3. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and is measured on an Apple M4 Pro (macOS, clang 21); 01_locality.c is also run as x86-64 under Rosetta 2. Timing numbers are from one run and labelled as such. Code: code/lecture09/. Reading time: ~75 minutes; ~15 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain the CPU–memory gap and why it has widened, and what SRAM, DRAM, disks and SSDs each contribute.
  2. Define temporal and spatial locality and judge a loop’s locality by eye.
  3. Explain how a memory hierarchy of caches gives the illusion of a large, fast memory, and state the three kinds of cache miss (cold, conflict, capacity).
  4. Define the working set and relate it to cache effectiveness.
  5. Read a measurement that shows the hierarchy’s levels as plateaus in access time.

0.2 Prerequisites and scope

  • Lectures 5–6: array layout (row-major) and the process memory map.
  • Reality 3 (“memory matters, and it is not flat”) and Reality 4 (“performance is more than big-O”) from Lecture 1 become concrete here.
  • In scope: CS:APP §6.1 (storage technologies), §6.2 (locality), §6.3 (the hierarchy and general cache concepts). The detailed cache organization (sets, lines, blocks) is Lecture 10.

0.3 Section → code map

SectionIdeaDemo in code/lecture09/
§1the CPU–memory gap—
§2SRAM, DRAM, disks, SSDs—
§3locality, judged by eye01_locality.c
§4the hierarchy; three miss types; working set02_working_set.c

1. The CPU–memory gap

A processor needs data and instructions every cycle. If every access went to main memory, the CPU would spend almost all its time waiting. The slides’ “Huge CPU–Memory Gap”: over decades, CPU speed grew far faster than DRAM latency, so the cost of a memory access, measured in CPU cycles, grew from a handful to hundreds. This is the memory wall (the von Neumann bottleneck): the processor is rarely limited by arithmetic, and usually by moving data.

Two facts make a solution possible:

  • Smaller memories are faster (and cheaper per access in energy). A 32 KiB SRAM can answer in a few cycles; a 16 GiB DRAM cannot.
  • Programs do not access memory randomly. They exhibit locality (§3), so a small fast memory holding the right small subset can serve most accesses.

The answer is to stage data through a hierarchy (§4): keep the active subset in small fast memories close to the CPU, and the rest in large slow ones farther away.


2. Storage technologies (briefly)

The slides survey the levels; the essentials:

  • SRAM (static RAM): 6–8 transistors per bit, no refresh, ~1× access time, ~100× the cost of DRAM. Used for caches (on the CPU die).
  • DRAM (dynamic RAM): 1 transistor + 1 capacitor per bit, must be refreshed, ~10× slower than SRAM, cheap and dense. Used for main memory.
  • Disks (rotating): huge and cheap, but access time is dominated by mechanical seek and rotational latency — milliseconds, ~10⁶× a cache access. Geometry: platters, tracks, sectors.
  • SSDs (flash): no moving parts, much faster than disks for reads, but writes are slower and a block can only be erased a limited number of times (wear). Between DRAM and disk in the hierarchy.

Both SRAM and DRAM scaling are nearing physical limits, which is part of why the gap persists. The exact numbers are in CS:APP §6.1; the shape — each level roughly 10–100× slower and larger and cheaper than the one above — is what matters.


3. Locality

3.1 Two kinds

Locality is the tendency of programs to reuse data and instructions with addresses near, or equal to, ones used recently:

  • Temporal locality: a recently referenced item is likely to be referenced again soon (a loop variable, a frequently-called function).
  • Spatial locality: items with nearby addresses tend to be referenced close together in time (the next array element, the next instruction).

The slides’ example #1:

long sum = 0;
for (int i = 0; i < n; i++) sum += a[i];
return sum;

sum has temporal locality (touched every iteration — a compiler keeps it in a register). The array a has spatial locality (stride-1 scan: a[0], a[1], …). The instructions have both: fetched in sequence (spatial), looped over (temporal).

3.2 Judging locality by eye

The slides claim — and it is true — that you can look at a loop and estimate its locality. The key skill is to find the stride of the inner loop over each array. For a row-major C array (Lecture 5), a[i][j] and a[i][j+1] are adjacent; a[i][j] and a[i+1][j] are N elements apart.

int sum_rows(int a[M][N]) { for i: for j: sum += a[i][j]; }   // stride 1: GOOD
int sum_cols(int a[M][N]) { for j: for i: sum += a[i][j]; }   // stride N: POOR

Both touch every element exactly once and do identical arithmetic. The difference is pure access pattern. The 3-D example is fixed the same way: permute the loops so the last array subscript is the innermost loop, making the scan stride 1.

3.3 Feeling it

01_locality.c sums a 64 MiB matrix both ways:

  row order (stride 1)      0.24 ns/elem   16.80 GB/s   (good locality)
  column order (stride N)   3.30 ns/elem    1.21 GB/s   (poor locality)
  same sum: yes;  column order was 13.8x SLOWER

Same sum, same number of adds, 13.8× slower from access order alone (and 103.7× when the same code runs as x86-64 under Rosetta 2). The reason is the cache: data moves in 64-byte blocks (Lecture 10), so a stride-1 scan reuses each block for 16 ints before moving on, while a stride-N scan can touch a fresh block every element. Spatial locality turned one slow memory fetch into 16 fast ones.


4. The hierarchy

4.1 Caching, level by level

Each level caches the one below it: it holds a subset, in blocks, and serves what it has (a hit) far faster than fetching from below (a miss). The slides’ general picture, and the real Core i7 / Apple Silicon layout:

registers  <  L1 cache  <  L2 cache  <  L3 / last-level cache  <  main memory (DRAM)  <  SSD / disk
 ~0 cyc        ~4 cyc       ~10 cyc        tens of cyc              ~hundreds of cyc      ~10^5-10^6 cyc

A hit at level k avoids the cost of going to level k+1. Because locality makes most accesses hits at the fast upper levels, the whole hierarchy behaves almost like a memory as large as the bottom level and nearly as fast as the top. Caches between the CPU and DRAM are managed by hardware and invisible to software (you cannot name a cache line in C); the DRAM/disk boundary (virtual memory, Lectures 11–12) is managed by the OS.

4.2 The three kinds of miss

When an access misses, the slides classify why (CS:APP §6.3):

  • Cold (compulsory) miss: the first reference to a block — unavoidable; the block has never been seen. (Count: with 8 elements per block, scanning 16 elements costs 2 cold misses, one per block.)
  • Capacity miss: the working set is larger than the cache, so blocks are evicted and later re-fetched. Would miss even in a perfectly flexible cache of this size.
  • Conflict miss: the cache is big enough, but the placement policy maps several active blocks to the same location, so they evict each other. (Referencing blocks 0, 8, 0, 8, … where both map to the same set misses every time.) This is Lecture 10’s topic.

A clean way to separate them: cold misses are those an infinite cache would still have; capacity misses are the extra ones a finite but unrestricted cache adds; conflict misses are the further extra ones the real placement policy adds.

4.3 The working set

The working set is the data a program is actively using “now” (in a loop, say). Caches are most effective when the working set fits in the cache: then, after the cold misses, almost everything is a hit. Locality shrinks the working set — a stride-1 scan’s working set at any moment is one block, while a scattered access pattern’s is large.

4.4 Seeing the levels

02_working_set.c makes the hierarchy visible. It pointer-chases a randomly permuted cycle of a given size (random, so the prefetcher cannot help, and each access waits on the previous) and times one access:

  working set   ns/access
  2 KiB .. 128 KiB   ~0.74     (fits in L1)
  256 KiB            3.95      <-- stepped up to a slower level (L2)
  1 MiB .. 16 MiB    6-13      (L2)
  32 MiB             56.82     <-- stepped up (DRAM)
  64 MiB             94.50

The curve is a staircase, not a line: flat while the working set fits a level, stepping up when it spills to the next. The first plateau’s width (128 KiB here) is this machine’s L1 data cache — unusually large on Apple Silicon; an Intel box would step at 32 KiB. The last big step is the gap to DRAM, ~100× slower than L1. This is Reality 4 made concrete: the same O(n) pointer walk is dozens of times slower once n leaves the cache. (Exact ns vary by machine and run; the step structure is stable.)


Summary

  • The CPU–memory gap means a memory access costs hundreds of CPU cycles; the processor is usually limited by moving data, not by arithmetic (the memory wall).
  • Storage forms a spectrum: SRAM (fast, costly — caches), DRAM (dense, slower — main memory), SSD and disk (huge, slow — storage). Each level is ~10–100× slower, larger and cheaper than the one above.
  • Locality — temporal (reuse soon) and spatial (nearby soon) — is what makes a hierarchy work. You can judge a loop’s locality from the inner-loop stride; a stride-1 scan of a row-major array reuses each cache block, a stride-N scan does not (measured: 13.8× faster).
  • A memory hierarchy caches each level in the one below, in blocks, so hits at the fast upper levels make the whole look large and fast. Misses are cold, capacity or conflict.
  • The working set is the data in active use; caching is effective when it fits. Measured, access latency is a staircase: flat within a level, stepping up when the working set spills to the next.

Common pitfalls

  • Judging cost by operation count alone. Two O(n) loops can differ 10–100× in speed (the row/column sum). Count memory blocks touched, not just elements.
  • Assuming a column scan is fine because “it’s the same work”. Stride-N access on a row-major array wastes most of every cache block.
  • Forgetting the array layout. Row-major means the last subscript is contiguous; the innermost loop should vary it.
  • Expecting a prefetcher to save a scattered pattern. Hardware prefetching helps regular strides, not random pointer chasing.
  • Confusing capacity and conflict misses. A cache “big enough” can still thrash if the placement policy collides active blocks (Lecture 10).

Exercises

  1. Classify the locality. For for (i=0;i<n;i++) for (j=0;j<n;j++) s += a[j][i]; on a row-major a, what is the inner-loop stride over a, and is the locality good or poor?

    AnswerThe inner loop varies `j`, and `a[j][i]` to `a[j+1][i]` are `n` elements apart: stride `n`. Poor spatial locality. Swap the loops (vary `i` inside) for stride 1.
  2. Cold misses. A cache block holds 8 ints and starts empty. How many cold misses does for (i=0;i<64;i++) sum += a[i]; incur, if a is block-aligned?

    Answer64 ints / 8 per block = 8 blocks = 8 cold misses. The other 56 accesses are hits (spatial locality). If `a` is not aligned, you may touch 9 blocks → 9 cold misses.
  3. Miss type. A 1 MiB cache is scanned by a loop whose working set is 4 MiB, repeatedly. After the first pass, are the misses cold, capacity or conflict?

    AnswerCapacity: the working set (4 MiB) exceeds the cache (1 MiB), so blocks are evicted before reuse and re-fetched each pass. Not cold (not first reference) and not necessarily conflict (it would miss even in a fully flexible cache this size).
  4. Working set. Why does the staircase in demo 02 have flat regions rather than a smooth slope?

    AnswerWhile the whole working set fits in a cache level, essentially every access (after the cold misses) hits that level, so the per-access time is that level's latency — flat. Only when the set spills to the next level does the average time jump. The widths of the flats reveal the level sizes.
  5. Permute. Rewrite for (i) for (j) for (k) s += a[k][i][j]; (row-major a[M][N][N]) for stride-1 access.

    AnswerThe last subscript is `j`, so `j` must be innermost; `a[k][i][j]` to `a[k][i][j+1]` are adjacent. Order the loops `for (k) for (i) for (j)` — i.e. move `j` inside: `for (i) for (k) for (j)` also works as long as `j` is last. The point is `j` innermost.
  6. Numbers. A cache hit costs 1 cycle, a miss 100. Compare the average access time at 99% vs 97% hit rate.

    Answer99%: 1 + 0.01×100 = 2 cycles. 97%: 1 + 0.03×100 = 4 cycles. 99% is **twice** as fast as 97% — a small change in miss rate has a large effect, which is why miss rate (not hit rate) is the headline number.

No lab is released at this lecture, but it sets up cachelab (Lecture 10): part B of that lab is about rewriting a matrix transpose for locality, which is exactly the row-vs-column effect measured here, scaled up. The habit of thinking in cache blocks and working sets is what the lab rewards.

Further reading

  • CS:APP3e §6.1–6.3; practice problems 6.1–6.17. §6.1.2 (disk geometry) and §6.1.3 (SSDs) for the storage details summarized here.
  • The “Latency Numbers Every Programmer Should Know” table (Jeff Dean / Peter Norvig), for the orders of magnitude.
  • U. Drepper, “What Every Programmer Should Know About Memory” (2007) — long, but the definitive practical treatment.

Preview of Lecture 10: Cache memories

This lecture treated the cache as a black box that holds “blocks”. Lecture 10 opens it: a cache is organized by three parameters — S sets, E lines per set, B bytes per block — and an address splits into a tag, a set index and a block offset. You will see direct-mapped, set-associative and fully-associative caches, hits and the three misses in detail, write policies (write-back/write-allocate), the full memory mountain (throughput vs size and stride), and how blocking a matrix multiply turns an O(n³) memory-bound kernel cache-friendly — the ideas behind cachelab.


术语表 (Glossary, English → 中文)

English中文
memory hierarchy存储器层次结构
CPU–memory gap / memory wallCPU-内存鸿沟 / 内存墙
von Neumann bottleneck冯·诺依曼瓶颈
SRAM / DRAM静态 / 动态随机存取存储器
refresh刷新
cache高速缓存
main memory主存
disk (seek / rotational latency)磁盘(寻道 / 旋转延迟)
solid-state disk (SSD) / flash固态硬盘 / 闪存
wear (flash)磨损
locality局部性
temporal locality时间局部性
spatial locality空间局部性
stride步长
row-major order行优先存储
block (cache line)块(缓存行)
hit / miss命中 / 缺失
cold (compulsory) miss冷(强制)缺失
capacity miss容量缺失
conflict miss冲突缺失
working set工作集
hit rate / miss rate命中率 / 缺失率
hit time / miss penalty命中时间 / 缺失代价
read throughput (bandwidth)读吞吐量(带宽)
access latency访问延迟
prefetching预取
pointer chasing指针追逐
← 返回课程目录