---
title: Caches and pipelines, previewed
heading: How real processors go faster
eyebrow: C8 · Lesson 39 · Caches and pipelines, previewed
xp: 50
---

::: hook
The processor in this course does one instruction per clock and reaches memory in the same clock. Real processors can't, for two reasons. Main memory (DRAM) is slow: a core running at a few GHz finishes an instruction in under a nanosecond, while DRAM takes tens of nanoseconds to answer. And one clock period long enough for a whole instruction is a slow clock. Two ideas recover most of the speed: a cache, a small fast memory next to the core holding the data used recently, and a pipeline, which overlaps instructions like an assembly line. This lesson is a first look at both; S4 covers them in depth.

::: play
- The curve is the average time per memory access as the miss rate rises. Move the miss rate slider to the marker's spot and read the average.
- Make the miss penalty longer, as for slower DRAM. How much do a few percent of misses cost now?
- What miss rate doubles the average access time compared with a cache that always hits?
:::
:::

```sim plot
view: graph
x: m = 0..20 %
y: t = 0..45 ns
slider: h = 0.5..5 = 1 ns
slider: P = 20..200 = 60 ns
slider: r = 0..20 = 5
plot: h + m/100*P | label: average access time
marker: x = r | label: miss rate
readout: average access time = h + r/100*P ns
readout: times slower than all hits = (h + r/100*P)/h
```

::: predict
## A cache answers in 1 ns. Misses go to DRAM and cost 60 ns more. If 5% of accesses miss, what's the average access time?

- [ ] 1 ns
- [ ] 1.05 ns
- [x] 4 ns
- [ ] 60 ns

::: reveal
4 ns: every access pays the 1 ns hit time, and 5% of them also pay 60 ns, an average of 0.05 × 60 = 3 ns more. So even a 95% hit rate leaves accesses four times slower than a perfect cache. Miss rates matter a lot, which is why caches are built to exploit how programs actually use memory.
:::
:::

::: nameit
## Caches

**Locality.** Programs reuse what they used recently (temporal locality: a loop's instructions, its counter) and use what's next to it (spatial locality: the next element of an array). A cache keeps recently used data in fast SRAM beside the core.

**Lines.** A cache stores memory in lines (blocks), commonly 64 bytes. A miss brings in the whole line, so the neighbors of the missed word arrive with it.

**Average memory access time.**

$$\text{AMAT} = t_\text{hit} + m \cdot t_\text{miss penalty}$$

with m the fraction of accesses that miss.

**Finding a line (direct-mapped).** Each memory address can live in exactly one cache line. The address splits into three fields:

| tag | index | offset |
|---|---|---|
| the rest, stored to check it's the right line | which line, $\log_2(\text{lines})$ bits | which byte in the line, $\log_2(\text{line size})$ bits |

A 4 KiB cache with 16-byte lines has 256 lines: 4 offset bits, 8 index bits, and with 32-bit addresses a 20-bit tag. Set-associative caches let each address live in any of a few lines, which reduces the misses from two addresses fighting over one line.

## Pipelines

Split the single-cycle path into stages with a register between each: fetch (IF), decode and read registers (ID), execute (EX), memory (MEM) and write back (WB). Each stage works on a different instruction at once:

| cycle | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| `lw` | IF | ID | EX | MEM | WB | | |
| `add` | | IF | ID | EX | MEM | WB | |
| `sub` | | | IF | ID | EX | MEM | WB |

The clock period only has to cover the slowest stage, so it can be several times shorter. Each instruction still takes k cycles, but one finishes every cycle: N instructions in a k-stage pipeline take k + N − 1 cycles.

**Hazards** break the overlap:

- A **data hazard**: an instruction needs a result an earlier one hasn't written back yet. Forwarding passes the ALU's result straight to the next instruction; a load followed at once by a use of its value still costs a one-cycle stall.
- A **control hazard**: after a branch, the pipeline doesn't know which instruction comes next until the branch is resolved. Processors predict, and a wrong guess throws away the instructions fetched since.

Stalls raise the average cycles per instruction above 1: CPI = 1 + (stall cycles per instruction).
:::

```sim plot
view: graph
x: N = 1..60
y: S = 0..10
slider: k = 2..10 step 1 = 5
plot: N*k/(k + N - 1) | label: speedup of a k-stage pipeline over N instructions
plot: k | dashed | color: ch3 | label: the limit, k
readout: speedup over 20 instructions = 20*k/(k + 19)
```

The ideal speedup of a k-stage pipeline (with a clock k times faster) over N instructions: short runs don't gain much, because the pipeline takes k cycles to fill.


::: example
## A cache hits in 1 ns and misses 4% of the time with a 60 ns miss penalty. What is the average memory access time?

::: solution
1. **Average memory access time.**
   $$\begin{aligned} t &= 1 + 0.04 \times 60 \\ &= 3.4\ \text{ns} \end{aligned}$$
2. **Without the cache.** Every access would take about 61 ns.

**Answer:** 3.4 ns.
:::
:::

::: example
## Split the address 0x00012345 for a direct-mapped 4 KiB cache with 16-byte lines.

::: solution
1. **Offset.** 16-byte lines take 4 offset bits: 0x5.
2. **Index.** 256 lines take 8 index bits: 0x34.
3. **Tag.** The other 20 bits are the tag: 0x00012.

**Answer:** tag 0x00012, index 0x34 and offset 0x5.
:::
:::

::: example
## A cache hits in 1 ns, and a miss costs 50 ns. What miss rate keeps the average access at 2 ns?

::: solution
1. **Set up the condition.**
   $$1 + m \times 50 \le 2$$
2. **Solve it.** $m \le 2\%$, a hit rate of at least 98%.
3. **Sensitivity.** Each extra percent of misses adds half a nanosecond, half the hit time again.
4. **A longer penalty.** Doubling the miss penalty halves the miss rate you can afford, which is why caches matter more as memory falls further behind the processor.

**Answer:** a miss rate of at most 2%, a hit rate of at least 98%.
:::
:::

::: check
given: h = 1 | 2; r = 2 | 5 | 10; P = 50 | 80 | 100
answer: h + r/100*P
unit: ns
tolerance: 0.5%

## A cache hits in {h} ns, a miss costs {P} ns more, and {r}% of accesses miss. What's the average access time?

::: right
Right: {answer}.
:::

::: misses
- [r/100*P] Every access pays the hit time too.
- [h + r*P] The miss rate is {r}%, a fraction of {r}/100.
- [any] Not yet. $t_\text{hit} + m \cdot t_\text{penalty}$.
:::
:::

::: check
kind: parts
given: C = 1 | 4 | 16 | 64; B = 16 | 32 | 64

## A direct-mapped cache holds {C} KiB in {B}-byte lines, for 32-bit addresses.

::: part
answer: round(log(B)/log(2))
tolerance: 0

### How many offset bits?

::: misses
- [any] Enough to pick one of {B} bytes in a line.
:::
:::

::: part
answer: round(log(1024*C/B)/log(2))
tolerance: 0

### How many index bits?

::: misses
- [round(log(1024*C)/log(2))] The index picks a line, so count lines: {C} KiB / {B} bytes.
- [any] Enough to pick one of the cache's lines: {C} × 1024 / {B} of them.
:::
:::

::: part
answer: 32 - round(log(1024*C)/log(2))
tolerance: 0

### How many tag bits?

::: misses
- [any] The tag is what's left of the 32 bits after the index and the offset.
:::
:::

::: right
Right. Offset and index together cover the cache's size, so the tag is 32 bits minus $\log_2$ of the size in bytes.
:::
:::

::: check
given: k = 4 | 5 | 6; N = 10..100 int
answer: k + N - 1
tolerance: 0

## A {k}-stage pipeline with no stalls runs {N} instructions. How many cycles from the first fetch to the last write back?

::: right
Right: {answer}. The first instruction takes {k} cycles to come out; after that one finishes every cycle.
:::

::: misses
- [k*N] That's with no overlap, one instruction at a time.
- [N] The first instruction takes {k} cycles to get through.
- [any] Not yet. {k} cycles for the first, then one more for each of the others.
:::
:::

::: check
given: L = 20 | 25 | 30; B = 10 | 15 | 20; w = 20 | 40
answer: 1 + L/100*0.5 + B/100*w/100*2
tolerance: 0.5%

## On a 5-stage pipeline, {L}% of instructions are loads, and half of those are followed at once by an instruction that uses the loaded value (1 stall cycle each). {B}% are branches, and {w}% of those are mispredicted (2 cycles lost each). What's the average CPI?

::: right
Right: {answer}. Each kind of stall adds its frequency times its cost.
:::

::: misses
- [1 + L/100 + B/100*w/100*2] Only half of the loads stall.
- [L/100*0.5 + B/100*w/100*2] Add the 1 cycle every instruction takes anyway.
- [any] Not yet. 1 + (stall cycles per instruction), summed over both causes.
:::
:::

::: check
kind: choice

## A loop adds up a large array one 4-byte element at a time. Why does a cache with 64-byte lines speed up its loads even though each element is used only once?

- [x] Each miss brings in the next 15 elements too
- [ ] The cache remembers the sum
- [ ] Every element is loaded many times
- [ ] Caches make DRAM itself faster

::: right
Right: spatial locality. One miss in 16 loads, instead of one in every load.
:::

::: misses
- [2] A cache holds copies of memory; it doesn't store results like the sum.
- [3] Here each element is used once; it's the neighbors that help.
- [4] DRAM is just as slow; the cache avoids going to it.
:::
:::

::: check
kind: match

## Match each term to what it means.

- data hazard :: an instruction needs a result that isn't written back yet
- control hazard :: the next instruction depends on a branch that hasn't been decided
- forwarding :: passing a result straight from the ALU to the next instruction
- stall :: holding an instruction back a cycle, leaving a bubble
- cache line :: the block of memory a miss brings in

::: right
Right. Pipelines keep running at one instruction per cycle until one of these hazards forces a bubble.
:::
:::

::: check
kind: parts
given: h = 1 | 2; P = 40 | 80 | 100; T = 3 | 5

## A cache hits in {h} ns and a miss costs {P} ns.

::: part
answer: (T - h)/P*100
unit: %
tolerance: 0.5%

### What's the largest miss rate that keeps the average at {T} ns?

::: misses
- [any] $h + mP = T$.
:::
:::

::: part
answer: h + 0.01*P
unit: ns
tolerance: 0.5%

### What's the average at a 1% miss rate?

::: misses
- [any] $h + 0.01P$.
:::
:::
:::

::: check
kind: parts
given: C = 4 | 16 | 64; L = 16 | 32 | 64

## A direct-mapped {C} KiB cache has {L}-byte lines and 32-bit addresses.

::: part
answer: round(log(L)/log(2))
tolerance: 0

### How many offset bits?

::: misses
- [any] $\log_2$ of the line size.
:::
:::

::: part
answer: round(log(C*1024/L)/log(2))
tolerance: 0

### How many index bits?

::: misses
- [any] $\log_2$ of the number of lines.
:::
:::

::: part
answer: round(32 - log(C*1024)/log(2))
tolerance: 0

### How many tag bits?

::: misses
- [any] What's left of the 32.
:::
:::
:::

::: explain
## A pipelined processor doesn't finish any single instruction faster than a single-cycle one. Why does it still run programs faster?

::: model
Each instruction still passes through every stage, so its own start-to-finish time is about the same (a little longer, because of the registers between stages). But the stages work on different instructions at the same moment: while one instruction executes, the next is being decoded and the one after is being fetched. Once the pipeline is full, one instruction finishes every cycle, and each cycle is only as long as the slowest stage rather than the whole path. So the throughput, instructions finished per second, rises by up to the number of stages, even though the latency of each instruction doesn't fall.
:::
:::

::: practice

::: check
given: h = 0.5 | 1 | 3; r = 1 | 3 | 8; P = 40 | 120
answer: h + r/100*P
unit: ns
tolerance: 0.5%

## Hit {h} ns, penalty {P} ns, miss rate {r}%. AMAT?

::: misses
- [r/100*P] Plus the hit time.
- [any] $t_\text{hit} + m \cdot t_\text{penalty}$.
:::
:::

::: check
given: k = 3 | 5 | 7 | 12; N = 20..500 int
answer: k + N - 1
tolerance: 0

## {N} instructions through a {k}-stage pipeline, no stalls. Cycles?

::: misses
- [k*N] They overlap.
- [any] k + N − 1.
:::
:::

::: check
given: C = 2 | 8 | 32; B = 16 | 64
answer: round(log(1024*C/B)/log(2))
tolerance: 0

## Index bits for a {C} KiB direct-mapped cache with {B}-byte lines?

::: misses
- [round(log(1024*C)/log(2))] Count lines: size / line size.
- [any] $\log_2$ of the number of lines.
:::
:::

::: check
given: L = 15 | 30; B = 12 | 18; w = 10 | 30
answer: 1 + L/100*0.5 + B/100*w/100*2
tolerance: 0.5%

## {L}% loads (half followed by a use: 1 stall), {B}% branches ({w}% mispredicted: 2 cycles). CPI?

::: misses
- [any] 1 + the stall cycles per instruction.
:::
:::
:::
