Lecture 10 · Cache memories

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

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 10 (Sep 24), slide deck 10-cache-memories. Reading: CS:APP3e §6.4–6.7. Lab: L3 (attacklab) is due; L4 (cachelab) is out. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes. The cache mechanics are reproduced by a Python teaching simulator (cachesim.py), and the performance effects are measured on an Apple M4 Pro (macOS, clang 21). Timing numbers are from one run. Academic integrity. cachesim.py is a teaching tool — it reads no valgrind trace and has no cache-parameter command line. It is not the cachelab csim.c you must write, and these notes contain none of that solution. Code: code/lecture10/. Reading time: ~95 minutes; ~30 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Split an address into tag / set index / block offset for a cache of given (S, E, B), and simulate hits and misses.
  2. Explain direct-mapped, set-associative and fully-associative caches, and how associativity trades conflict misses for comparators.
  3. State the write policies (write-back / write-allocate vs write-through / no-write-allocate) and what a dirty bit is for.
  4. Compute miss rate and average access time, and explain why a small miss-rate change matters so much.
  5. Read the memory mountain and write cache-friendly code: choose loop order by stride and apply blocking.

0.2 Prerequisites and scope

  • Lecture 9: locality, the hierarchy, the three miss types, the working set.
  • Lecture 5: array layout (row-major), which decides a loop’s stride.
  • In scope: CS:APP §6.4 (cache organization), §6.5 (writing cache-friendly code), §6.6 (the memory mountain and matrix multiply / blocking), §6.7 (cache effects in practice).

0.3 Section → code map

SectionIdeaDemo in code/lecture10/
§1organization: S, E, B; tag/set/offset01_cache_sim.py
§2direct-mapped, set-associative; the three misses01_cache_sim.py
§3writes: policies and the dirty bit—
§4performance metrics—
§5the memory mountain02_memory_mountain.c
§6cache-friendly code: loop order and blocking03_matmul.c, 04_blocking.c

1. Cache organization: S, E, B

A cache is defined by three parameters:

  • S = 2ˢ sets,
  • E = 2ᵉ lines per set (the associativity),
  • B = 2ᵇ bytes per block (the data a line holds).

Total data capacity is S × E × B. Each line also holds a valid bit and a tag. A byte address is split into three fields, using the middle bits for the set index:

      [    tag    ][ set index ][ block offset ]
          t bits       s bits        b bits
  • The block offset (low b bits) picks the byte within the block.
  • The set index (next s bits) picks the set.
  • The tag (the rest) identifies which block is in the line.

To read, the cache uses the set index to find the set, checks each line’s valid bit and tag against the address’s tag, and on a match (a hit) returns the byte at the offset. (Why the middle bits for the set? So that consecutive blocks spread across sets instead of piling into one — see the slides’ “Why Index Using Middle Bits?”.)

01_cache_sim.py PART A shows the split for the slides’ tiny cache (4-bit addresses, S=4, E=1, B=2, so t=1, s=2, b=1):

  addr 7 = 0111 -> tag 1 set 3 off 1
  addr 8 = 1000 -> tag 1 set 0 off 0

2. Direct-mapped, set-associative, and the three misses

2.1 The slides’ simulations

With E = 1 (direct-mapped) each block has exactly one place it can go. The slides’ trace 0, 1, 7, 8, 0 on the S=4, E=1, B=2 cache (demo 01 PART A):

  addr 0 : miss       (cold)      set 0 <- block 0
  addr 1 : hit                    (same block as 0)
  addr 7 : miss       (cold)      set 3 <- block 3
  addr 8 : miss+evict (cold)      set 0 <- block 4 (evicts block 0)
  addr 0 : miss+evict (conflict)  set 0 <- block 0 (evicts block 4)
  -> hits=1 misses=4 evictions=2

The last 0 misses because block 4 (address 8) and block 0 both map to set 0 and keep evicting each other: a conflict miss. With E = 2 (2-way set-associative, S=2, B=2) set 0 can hold both blocks, so the last 0 hits:

  addr 0 : miss    addr 1 : hit    addr 7 : miss    addr 8 : miss    addr 0 : hit
  -> hits=2 misses=3

Associativity turns the conflict miss into a hit, at the cost of checking E tags per access. A fully-associative cache (one set, E = all lines) has no conflict misses at all, but needs E comparators — practical only for small caches (like the TLB, Lecture 11).

2.2 Separating conflict from capacity

Demo 01 PART B makes the distinction concrete. Two addresses 64 bytes apart map to the same set in an 8-set, 8-byte-block cache; alternating them thrashes a cache that is seven-eighths empty:

  accesses 0,64,0,64,... : hits=0 misses=8 (cold=2 conflict=6)
  same trace, 2-way      : hits=6 misses=2

Every repeat is a conflict miss — the cache has room, but the placement policy collides the two blocks. A capacity miss is different: scanning more distinct blocks than the cache holds misses even with full associativity:

  6 blocks through a 4-block cache, 3 passes : (capacity=8)

The simulator classifies each miss by comparing against a same-capacity fully-associative cache (conflict if that would have hit) and an infinite one (cold if never seen before) — a classification the slides describe and cachelab does not require.


3. Writes

Reads are the easy case. On a write, the data now exists in several places (L1, L2, …, memory), so two policy choices arise (slides “What about writes?”):

  • Write-hit: write-through (update memory immediately) or write-back (update only the cache line, and write it to memory later, when it is evicted). Write-back needs a dirty bit per line, set on a write and cleared on eviction, so the cache knows whether an evicted line must be written out.
  • Write-miss: write-allocate (load the block into the cache, then write) or no-write-allocate (write straight to memory, skip the cache).

The common pairings are write-through + no-write-allocate and, more often today, write-back + write-allocate (slide 21): a write to an absent block fetches it (like a read miss) and then writes the cache copy, marking it dirty; the block goes to memory only when evicted. Write-back + write-allocate wins when writes have locality (repeated writes to the same block hit after the first), which is usual.

The real Intel Core i7 / Apple Silicon hierarchy (slides): per-core L1 split into instruction and data caches, a per-core unified L2, and a large L3 (Intel) or cluster L2 (Apple) shared by all cores, then DRAM.


4. Performance metrics

  • Miss rate = misses / accesses = 1 − hit rate. Typical L1 miss rates are a few percent; L2 well under 1%.
  • Hit time = cycles to deliver a line already in the cache (≈ 4 for L1, ≈ 10 for L2).
  • Miss penalty = extra cycles for a miss (≈ 50–200 for DRAM, and rising).

Average access time = hit time + miss rate × miss penalty. The slides’ striking example (hit time 1, miss penalty 100):

  97% hits: 1 + 0.03 × 100 = 4 cycles
  99% hits: 1 + 0.01 × 100 = 2 cycles

99% hits is twice as fast as 97%. Because the miss penalty is so large, a tiny change in miss rate swings performance hugely — which is why the headline number is miss rate, not hit rate, and why the rest of this lecture is about lowering it.


5. The memory mountain

The slides’ single most compact picture of a memory system is the memory mountain: read throughput (MB/s) as a function of both working-set size (temporal locality — which cache the data fits in) and stride (spatial locality — how much of each block is used). 02_memory_mountain.c measures it with the slides’ 4×-unrolled test function:

  size\str s1       s4       s8       s16      s32
  4K       93.2     85.8     72.2     53.4     32.5
  64K      93.7     89.4     75.7     54.6     31.3
  256K     79.8     33.8     18.3     15.7     14.1
  16M      78.7     29.9     15.2     11.5     10.9
  128M     70.5     24.7     13.2     3.3      2.9     (GB/s)

Reading the terrain:

  • Back ridge (small size, any stride): ~93 GB/s — data in L1, served at full speed.
  • Down a column: throughput steps down as the working set spills from L1 to L2 to DRAM — the terraces are the cache sizes, lost temporal locality.
  • Across a row: throughput falls as the stride grows, because each 64-byte block (8 longs) delivers fewer used elements — lost spatial locality.
  • Far corner (large size, large stride): ~3 GB/s — the memory wall, both localities gone.
  • Past stride 8 (= 64 bytes, one block) each access needs its own block, so larger strides stop hurting and the slope flattens.

The whole of this lecture’s advice is “stay toward the top-left of the mountain”: small working sets (temporal) and small strides (spatial).


6. Writing cache-friendly code

6.1 Loop order: matrix multiply

Matrix multiply is O(n³) in every loop order, but the inner loop’s stride through each matrix sets the miss rate (Lecture 9). The slides analyze the six orders; the simulator confirmed the ranking (demo 01 PART C), and 03_matmul.c measures it:

  order  GFLOP/s   vs fastest   inner-loop stride
  ikj    15.68     1.0x         inner j: B,C stride 1
  kij    10.97     1.4x         inner j: B,C stride 1
  jik     2.65     5.9x         inner k: A stride 1, B stride n
  ijk     2.61     6.0x         inner k: A stride 1, B stride n
  kji     0.81    19.3x         inner i: A,C stride n
  jki     0.75    20.8x         inner i: A,C stride n

A 20× spread for identical arithmetic (and identical results, checked). The pattern follows the slides’ miss analysis exactly:

  • kij / ikj (2 loads + 1 store, all stride-1 inner): ~0.5 misses/iter — fastest, and -O2 vectorizes the stride-1 inner loop.
  • ijk / jik (stride-1 A, stride-n B): ~1.25 misses/iter — middle.
  • jki / kji (stride-n A and C): ~2.0 misses/iter — slowest; the compiler cannot vectorize a stride-n inner loop.

The lesson: for C’s row-major layout, make the innermost loop vary the last index of the matrices it reads.

6.2 Blocking

Even the best loop order re-reads the matrices from memory O(n) times for large n: the naive multiply has about (9/8) n³ misses (slides’ “Cache Miss Analysis”). Yet the computation has huge inherent temporal locality — it uses 3n² input elements to do 2n³ operations, so each element is used O(n) times. Blocking realizes that locality by computing the product in small tiles that fit in cache and reusing each tile fully before moving on. 04_blocking.c tiles the multiply and compares with the textbook ijk order:

  version          GFLOP/s   speedup       (n = 1536)
  naive (ijk)       2.13      1.0x
  blocked B=32     12.87      6.1x
  blocked B=128    13.35      6.3x

A 6.3× speedup from reordering the same arithmetic. The slides’ analysis: with tile size B chosen so three B×B tiles fit in cache (3B² < C), blocking reduces misses to about 1/(4B) n³ — roughly B times fewer. Pick the largest B that still fits; too small loses spatial locality, too large no longer fits.

Plan vs reality. Blocking helped little when compared against the already-cache-friendly kij order (≈1.1× even at n=2048) — Apple Silicon’s large caches, strong prefetcher and -O2 vectorization already serve the stride-1 kij well. The 6.3× appears against the naive ijk order, whose stride-n access blocking repairs. On the slides’ Intel i7 the gains are larger across the board; the shape of the result (blocking recovers the lost locality) is the same.


Summary

  • A cache is (S sets, E lines/set, B bytes/block); an address splits into tag / set index / block offset, using the middle bits for the set.
  • Direct-mapped (E=1) is simplest but suffers conflict misses; set-associative (E>1) trades comparators for fewer conflicts; fully-associative has none. Cold, conflict and capacity misses are distinguished by comparing against infinite and fully-associative caches.
  • On writes, write-back + write-allocate (with a dirty bit) is the common modern policy; it pays off when writes have locality.
  • Average access time = hit time + miss rate × miss penalty; because the penalty is ~100×, 99% hits is twice as fast as 97%, so miss rate is the number that matters.
  • The memory mountain shows throughput falling down the size axis (temporal locality, the cache terraces) and across the stride axis (spatial locality, the block). Good code stays top-left.
  • Cache-friendly code: choose the loop order with a stride-1 inner loop (measured 20× effect in matrix multiply) and block large computations into cache-sized tiles (measured 6× over the naive order).

Common pitfalls

  • Counting operations instead of misses. All six matrix-multiply orders do the same multiplies; they differ 20× because of the miss rate.
  • Confusing associativity with capacity. Adding ways (E) removes conflict misses but not capacity misses; a bigger cache (or blocking) is needed for those.
  • A column-major inner loop on a row-major array. Stride-n access wastes most of every cache block — the single most common locality bug.
  • Blocking an already-cache-friendly loop and expecting miracles. Blocking repairs lost locality; if the loop order is already stride-1 and the machine prefetches well, the gain can be small. Measure.
  • Choosing a block size by guessing. The best B depends on the cache size (3B² < C); find it by measuring, as demo 04 does.
  • Ignoring the write policy. With write-allocate, a write miss fetches the whole block; streaming writes that never re-read can be slower than you expect.

Exercises

  1. Address split. A cache has S=64 sets, B=64-byte blocks. For a 48-bit address, how many bits are tag / set / offset?

    Answeroffset = log2 64 = 6; set = log2 64 = 6; tag = 48 − 6 − 6 = 36. Address = [36-bit tag][6-bit set][6-bit offset].
  2. Hit or miss. On the direct-mapped S=4, E=1, B=2 cache, give the hit/miss sequence for the byte trace 0, 2, 4, 2, 0.

    AnswerBlocks: 0→blk0/set0, 2→blk1/set1, 4→blk2/set2, 2→blk1/set1, 0→blk0/set0. Sets differ, so no evictions: miss, miss, miss, hit, hit. 3 misses (all cold), 2 hits.
  3. Conflict vs capacity. A 4-set, 1-way, 8-byte-block cache repeatedly scans blocks at byte addresses 0, 32, 64, 96 (all map to set 0). Are the repeat misses conflict or capacity?

    AnswerAll four map to set 0 (block numbers 0,4,8,12, each mod 4 = 0). In a direct-mapped cache they evict each other: conflict misses. But a fully-associative cache of the same 4-block capacity would hold exactly these 4 blocks and hit — so by the strict definition they are conflict (the policy, not the capacity, is to blame). With a fifth block they would become capacity misses.
  4. Average access time. L1 hit time 4 cycles, miss rate 3%, miss penalty 100 cycles. What is the average access time, and what does it become at 1% miss rate?

    Answer4 + 0.03×100 = 7 cycles. At 1%: 4 + 0.01×100 = 5 cycles. Cutting the miss rate from 3% to 1% improves average access time by ~29%.
  5. Loop order. For for (j) for (i) for (k) c[i][j] += a[i][k]*b[k][j]; (row-major), give the inner-loop stride through a, b and c, and rank this order’s locality.

    AnswerInner loop is k: `a[i][k]` stride 1, `b[k][j]` stride n, `c[i][j]` constant (loop-invariant, a register). This is the jik/ijk family: one stride-1 and one stride-n stream, ~1.25 misses/iter — middling, worse than kij, better than jki.
  6. Blocking math. A cache holds C = 32 KiB. Matrices are doubles (8 bytes). What is the largest square tile B (in elements) with 3B² × 8 ≤ C, and roughly how many times fewer misses than the naive (9/8)n³?

    Answer3B²×8 ≤ 32768 → B² ≤ 1365 → B ≤ 36, so B ≈ 36 (a power-of-two choice would be 32). Misses drop from (9/8)n³ to ~1/(4B) n³, i.e. about (9/8)/(1/(4·36)) ≈ 162× fewer in the ideal model (real speedups are smaller because of prefetching and other effects).

cachelab has two parts. Part A: write a cache simulator (csim.c) that reads a valgrind memory trace and reports hits, misses and evictions for a given (s, E, b). The simulator here supports understanding that task — the tag/set/offset split, LRU, the three miss types — but is deliberately not that deliverable (it is Python, reads no trace, and has no -s -E -b -t interface); you must write your own. Part B: optimize a matrix transpose for a given small cache, which is exactly the loop-order-and-blocking work of §6, scaled to fit the lab’s cache. These notes contain no lab solution; demos 01, 03 and 04 rehearse the skills.

Further reading

  • CS:APP3e §6.4–6.7; practice problems 6.18–6.46. §6.6.2 (the memory mountain) and §6.6.3 (blocking) for the measurements here.
  • The slides’ “Why Index Using Middle Bits?” additional slide, for the set-index choice.
  • U. Drepper, “What Every Programmer Should Know About Memory” (2007), §3 and §6, for associativity, prefetching and blocking in depth.

Preview of Lecture 11: Virtual memory — concepts

So far addresses have been treated as if they name physical memory directly. Lectures 11–12 reveal that every address your program uses is a virtual address, translated by hardware (the MMU) through page tables to a physical one, with a TLB caching the translations — itself a cache, indexed and tagged just like the ones here. Virtual memory gives each process its own private address space (explaining Lecture 6’s ASLR), protects processes from each other, and lets memory be paged to disk on demand. Lecture 11 builds the concepts; Lecture 12 works a full translation on a real hierarchy.


术语表 (Glossary, English → 中文)

English中文
cache memory高速缓存
set / line / block组 / 行 / 块
associativity (E)相联度
tag / set index / block offset标记 / 组索引 / 块内偏移
valid bit / dirty bit有效位 / 脏位
direct-mapped cache直接映射缓存
set-associative cache组相联缓存
fully-associative cache全相联缓存
hit / miss命中 / 缺失
cold / conflict / capacity miss冷 / 冲突 / 容量 缺失
eviction / replacement (LRU)驱逐 / 替换(最近最少使用)
write-through / write-back写直达 / 写回
write-allocate / no-write-allocate写分配 / 非写分配
miss rate / hit rate缺失率 / 命中率
hit time / miss penalty命中时间 / 缺失代价
average access time平均访问时间
memory mountain存储器山
read throughput (bandwidth)读吞吐量(带宽)
cache-friendly code缓存友好代码
loop order循环顺序
blocking / tiling分块
strength of locality (temporal / spatial)局部性(时间 / 空间)
prefetching / vectorization预取 / 向量化
← 返回课程目录