---
title: "A computer of your own: performance"
heading: Measuring where a processor's time goes, the iron law of instructions, cycles per instruction and clock rate, the hazards that stall a five-stage pipeline, profiling an execution trace for loads, branches and stalls, and what the compiler's optimizer changes
eyebrow: D13 · Lesson 13 · A computer of your own
xp: 120
---

::: hook
Your core runs one instruction per cycle, but at a slow clock, because each cycle must fit fetch, decode, execute, memory and write-back end to end. A pipelined core overlaps them and clocks several times faster, at the price of **hazards**: a value loaded from memory isn't ready for the very next instruction, and a taken branch has already let the wrong instructions start. How much that costs depends on the program, so you measure it: run the program, record every instruction, and count. The same counts show what the compiler's optimizer bought.
:::

::: play
- The CRC program compiled at -O0, without optimization, on the simulator. Compare its listing with lesson 12's -O1 version: every variable lives on the stack, so almost every line loads and stores.
- Watch sp and the memory traffic: at -O0 the CRC runs 1686 instructions, at -O1 1042, for the same result.
- Notice that the branches and jumps are the same in both: the optimizer removed memory traffic, not control flow.

```sim cpu
c:
#include "board.h"

const char message[] = "123456789";

uint32_t crc16(const char *s) {
    uint32_t reg = 0xFFFF;
    while (*s) {
        reg ^= (uint32_t)(unsigned char)*s++ << 8;
        for (int k = 0; k < 8; k++) {
            if (reg & 0x8000) reg = (reg << 1) ^ 0x1021;
            else reg = reg << 1;
            reg &= 0xFFFF;
        }
    }
    return reg;
}

int main(void) {
    uint32_t c = crc16(message);
    print(c);
    LEDS = c & 0xFF;
    return 0;
}
asm:
    .text
_start:
    call main
    ebreak

crc16:
    addi sp, sp, -32        #@5
    sw ra, 28(sp)           #@5
    sw s0, 24(sp)           #@5
    addi s0, sp, 32         #@5
    sw a0, -12(s0)          #@5
    li t0, 0xffff           #@6
    sw t0, -16(s0)          #@6
.L1:
    lw t0, -12(s0)          #@7
    lbu t0, 0(t0)           #@7
    beqz t0, .L2            #@7
    lw t0, -16(s0)          #@8
    lw t1, -12(s0)          #@8
    mv t2, t1               #@8
    addi t1, t1, 1          #@8
    sw t1, -12(s0)          #@8
    lbu t2, 0(t2)           #@8
    slli t2, t2, 8          #@8
    xor t0, t0, t2          #@8
    sw t0, -16(s0)          #@8
    sw zero, -20(s0)        #@9
.L3:
    lw t0, -20(s0)          #@9
    li t1, 8                #@9
    bge t0, t1, .L5         #@9
    lw t0, -16(s0)          #@10
    li t1, 0x8000           #@10
    and t0, t0, t1          #@10
    beqz t0, .L6            #@10
    lw t0, -16(s0)          #@10
    slli t0, t0, 1          #@10
    li t1, 0x1021           #@10
    xor t0, t0, t1          #@10
    sw t0, -16(s0)          #@10
    j .L7                   #@10
.L6:
    lw t0, -16(s0)          #@11
    slli t0, t0, 1          #@11
    sw t0, -16(s0)          #@11
.L7:
    lw t0, -16(s0)          #@12
    li t1, 0xffff           #@12
    and t0, t0, t1          #@12
    sw t0, -16(s0)          #@12
.L4:
    lw t0, -20(s0)          #@9
    addi t0, t0, 1          #@9
    sw t0, -20(s0)          #@9
    j .L3                   #@9
.L5:
    j .L1                   #@7
.L2:
    lw a0, -16(s0)          #@15
.Lret_crc16:
    lw ra, 28(sp)           #@16
    lw s0, 24(sp)           #@16
    addi sp, sp, 32         #@16
    ret                     #@16

main:
    addi sp, sp, -16        #@18
    sw ra, 12(sp)           #@18
    sw s0, 8(sp)            #@18
    addi s0, sp, 16         #@18
    la a0, message          #@19
    call crc16              #@19
    mv t0, a0               #@19
    sw t0, -12(s0)          #@19
    lw t0, -12(s0)          #@20
    lui t1, 0x20            #@20
    sw t0, 16(t1)           #@20
    lw t0, -12(s0)          #@21
    andi t0, t0, 255        #@21
    lui t1, 0x20            #@21
    sw t0, 0(t1)            #@21
    li a0, 0                #@22
.Lret_main:
    lw ra, 12(sp)           #@23
    lw s0, 8(sp)            #@23
    addi sp, sp, 16         #@23
    ret                     #@23

    .data
message:
    .byte 49, 50, 51, 52, 53, 54, 55, 56, 57, 0
show: a0, sp
hex: sp
leds: on
out: on
speed: 500
```

::: predict
## In a five-stage pipeline with forwarding, which of these still costs a stall cycle?

- [ ] An add whose result the next instruction uses
- [x] A load whose result the next instruction uses
- [ ] A store followed by an add
- [ ] Two adds in a row that use different registers

::: reveal
Forwarding hands an ALU result straight to the next instruction, but a load's data only arrives at the end of the memory stage, one cycle too late for an instruction right behind it: a **load-use** stall. Taken branches and jumps cost more, two cycles here, because the pipeline has already fetched two instructions that must be thrown away.
:::
:::

::: nameit
## The iron law

$$T = N \times \text{CPI} \times \frac{1}{f}$$

Instructions N depend on the program and compiler, cycles per instruction on the microarchitecture and the program's hazards, and the clock f on the circuit (S4).

## A pipeline model

For a classic five-stage pipeline with forwarding:

- every instruction takes one cycle;
- a load whose destination is read by the very next instruction adds one stall;
- a taken branch or any jump adds two cycles of fetched-and-flushed instructions.

So cycles = N + (load-use stalls) + 2 × (taken branches + jumps), and CPI = cycles/N.

## Profiling

Run the program on your core, record each executed instruction with its registers and whether it branched, and count. The lab's numbers for the CRC:

| | instructions | loads | load-use | taken + jumps | cycles | CPI |
|---|---|---|---|---|---|---|
| -O0 | 1686 | 423 | 183 | 51 + 116 | 2203 | 1.31 |
| -O1 | 1042 | 21 | 19 | 51 + 116 | 1395 | 1.34 |

The optimizer keeps variables in registers, so loads fall twentyfold and the stalls with them; control flow doesn't change, so the 334 cycles of branch penalty stay, and at -O1 they're a quarter of the time. That points at the next improvement: **branch prediction** (C8, S4).
:::

::: example
## At -O1 the CRC takes 1395 cycles on the pipeline. If the pipeline clocks at 200 MHz and the single-cycle core at 50 MHz, how do they compare?

::: solution
1. **Pipeline.**
   $$\begin{aligned} t &= \frac{1395}{200\ \text{MHz}} \\ &= 6.975\ \mu\text{s} \end{aligned}$$
2. **Single-cycle core.** One cycle for each of the 1042 instructions:
   $$\begin{aligned} t &= \frac{1042}{50\ \text{MHz}} \\ &= 20.8\ \mu\text{s} \end{aligned}$$
3. **Compare.** The pipeline is 3.0 times faster despite its CPI of 1.34, because its clock is 4 times faster.

**Answer:** 6.975 µs on the pipeline against 20.8 µs on the single-cycle core, 3.0 times faster.
:::
:::

::: example
## A perfect branch predictor would remove the 2-cycle penalty on taken branches and jumps. What would the CRC's CPI be at -O1?

::: solution
1. **Remove the penalties.** The 51 taken branches and 116 jumps each lose 2 cycles:
   $$\begin{aligned} N &= 1395 - 2 \times (51 + 116) \\ &= 1061\ \text{cycles} \end{aligned}$$
2. **CPI.** For 1042 instructions:
   $$\begin{aligned} \text{CPI} &= \frac{1061}{1042} \\ &= 1.02 \end{aligned}$$
3. **Real predictors.** Real predictors miss sometimes, and jumps through registers are harder to predict, so practical cores land in between.

**Answer:** a CPI of 1.02.
:::
:::

::: check
kind: python

## Profile execution traces and compare the optimizer's effect on cycles.

```python starter
MEM_SIZE = 0x30000
TEXT, DATA, STACK = 0x0, 0x1000, 0x10000

def sext(v, bits):
    # Sign-extend the low `bits` bits of v.
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

R_OPS = {(0, 0): 'add', (0, 0x20): 'sub', (1, 0): 'sll', (2, 0): 'slt', (3, 0): 'sltu',
         (4, 0): 'xor', (5, 0): 'srl', (5, 0x20): 'sra', (6, 0): 'or', (7, 0): 'and'}
I_OPS = {0: 'addi', 2: 'slti', 3: 'sltiu', 4: 'xori', 6: 'ori', 7: 'andi'}
LOADS = {0: 'lb', 1: 'lh', 2: 'lw', 4: 'lbu', 5: 'lhu'}
STORES = {0: 'sb', 1: 'sh', 2: 'sw'}
BRANCHES = {0: 'beq', 1: 'bne', 4: 'blt', 5: 'bge', 6: 'bltu', 7: 'bgeu'}

def decode(w):
    # One 32-bit instruction word to (name, rd, rs1, rs2, imm), with imm already sign-extended.
    op, rd, f3 = w & 0x7F, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op == 0x33:
        return R_OPS[(f3, f7)], rd, rs1, rs2, 0
    if op == 0x13:
        if f3 == 1:
            return 'slli', rd, rs1, 0, rs2
        if f3 == 5:
            return ('srai' if f7 else 'srli'), rd, rs1, 0, rs2
        return I_OPS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x03:
        return LOADS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x23:
        return STORES[f3], 0, rs1, rs2, sext((f7 << 5) | rd, 12)
    if op == 0x63:
        imm = ((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 63) << 5) | (((w >> 8) & 15) << 1)
        return BRANCHES[f3], 0, rs1, rs2, sext(imm, 13)
    if op == 0x37:
        return 'lui', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x17:
        return 'auipc', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x6F:
        imm = ((w >> 31) << 20) | (((w >> 12) & 255) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 1023) << 1)
        return 'jal', rd, 0, 0, sext(imm, 21)
    if op == 0x67:
        return 'jalr', rd, rs1, 0, sext(w >> 20, 12)
    if w == 0x00100073:
        return 'ebreak', 0, 0, 0, 0
    raise ValueError(f'unknown instruction {w:#010x}')

class CPU:
    def __init__(self, words, data=b''):
        self.mem = bytearray(MEM_SIZE)
        for k, w in enumerate(words):
            self.mem[TEXT + 4*k:TEXT + 4*k + 4] = (w & 0xFFFFFFFF).to_bytes(4, 'little')
        self.mem[DATA:DATA + len(data)] = bytes(data)
        self.x = [0]*32
        self.x[2] = STACK
        self.pc = TEXT
        self.count = 0

    def load(self, addr, n):
        return int.from_bytes(self.mem[addr:addr + n], 'little')

    def store(self, addr, n, value):
        self.mem[addr:addr + n] = (value & ((1 << 8*n) - 1)).to_bytes(n, 'little')

    def step(self):
        name, rd, rs1, rs2, imm = decode(self.load(self.pc, 4))
        a, b = self.x[rs1], self.x[rs2]
        u = lambda v: v & 0xFFFFFFFF
        nxt, val = self.pc + 4, None
        if name == 'ebreak':
            self.count += 1
            return False
        elif name == 'add': val = a + b
        elif name == 'sub': val = a - b
        elif name == 'and': val = a & b
        elif name == 'or': val = a | b
        elif name == 'xor': val = a ^ b
        elif name == 'sll': val = a << (b & 31)
        elif name == 'srl': val = u(a) >> (b & 31)
        elif name == 'sra': val = a >> (b & 31)
        elif name == 'slt': val = int(a < b)
        elif name == 'sltu': val = int(u(a) < u(b))
        elif name == 'addi': val = a + imm
        elif name == 'andi': val = a & imm
        elif name == 'ori': val = a | imm
        elif name == 'xori': val = a ^ imm
        elif name == 'slti': val = int(a < imm)
        elif name == 'sltiu': val = int(u(a) < u(imm))
        elif name == 'slli': val = a << imm
        elif name == 'srli': val = u(a) >> imm
        elif name == 'srai': val = a >> imm
        elif name == 'lui': val = imm
        elif name == 'auipc': val = self.pc + imm
        elif name in ('lb', 'lh', 'lw', 'lbu', 'lhu'):
            n = {'lb': 1, 'lh': 2, 'lw': 4, 'lbu': 1, 'lhu': 2}[name]
            val = self.load(u(a + imm), n)
            if name in ('lb', 'lh', 'lw'):
                val = sext(val, 8*n)
        elif name in ('sb', 'sh', 'sw'):
            self.store(u(a + imm), {'sb': 1, 'sh': 2, 'sw': 4}[name], b)
        elif name in ('beq', 'bne', 'blt', 'bge', 'bltu', 'bgeu'):
            taken = {'beq': a == b, 'bne': a != b, 'blt': a < b, 'bge': a >= b,
                     'bltu': u(a) < u(b), 'bgeu': u(a) >= u(b)}[name]
            if taken:
                nxt = self.pc + imm
        elif name == 'jal':
            val, nxt = self.pc + 4, self.pc + imm
        elif name == 'jalr':
            val, nxt = self.pc + 4, (a + imm) & ~1
        if val is not None and rd:
            self.x[rd] = sext(val, 32)
        self.pc = u(nxt)
        self.count += 1
        return True

    def run(self, limit=1000000):
        while self.count < limit and self.step():
            pass
        return self.count

def trace_program(words, data=b''):
    # Run a program on the core and record every instruction it executes as
    # (name, rd, rs1, rs2, taken), where taken says whether a branch went to its target.
    cpu, out = CPU(words, data), []
    while True:
        pc = cpu.pc
        name, rd, rs1, rs2, imm = decode(cpu.load(pc, 4))
        going = cpu.step()
        out.append((name, rd, rs1, rs2, name in BRANCHES.values() and cpu.pc != pc + 4))
        if not going:
            return out

# CRC-16 and the sieve compiled at -O0 and -O1.
CRC_O0 = [
    0x00000097, 0x0e0080e7, 0x00100073, 0xfe010113, 0x00112e23, 0x00812c23,
    0x02010413, 0xfea42a23, 0x000102b7, 0xfff28293, 0xfe542823, 0xff442283,
    0x0002c283, 0x08028c63, 0xff042283, 0xff442303, 0x00030393, 0x00130313,
    0xfe642a23, 0x0003c383, 0x00839393, 0x0072c2b3, 0xfe542823, 0xfe042623,
    0xfec42283, 0x00800313, 0x0662d063, 0xff042283, 0x00008337, 0x0062f2b3,
    0x02028063, 0xff042283, 0x00129293, 0x00001337, 0x02130313, 0x0062c2b3,
    0xfe542823, 0x0100006f, 0xff042283, 0x00129293, 0xfe542823, 0xff042283,
    0x00010337, 0xfff30313, 0x0062f2b3, 0xfe542823, 0xfec42283, 0x00128293,
    0xfe542623, 0xf9dff06f, 0xf65ff06f, 0xff042503, 0x01c12083, 0x01812403,
    0x02010113, 0x00008067, 0xff010113, 0x00112623, 0x00812423, 0x01010413,
    0x00001517, 0xf1050513, 0x00000097, 0xf14080e7, 0x00050293, 0xfe542a23,
    0xff442283, 0x00020337, 0x00532823, 0xff442283, 0x0ff2f293, 0x00020337,
    0x00532023, 0x00000513, 0x00c12083, 0x00812403, 0x01010113, 0x00008067,
]
CRC_O1 = [
    0x00000097, 0x080080e7, 0x00100073, 0x000105b7, 0xfff58593, 0x00054283,
    0x06028063, 0x00050293, 0x00150513, 0x0002c283, 0x00829293, 0x0055c5b3,
    0x00000613, 0x00800293, 0x02565e63, 0x000082b7, 0x0055f2b3, 0x00028c63,
    0x00159293, 0x00001337, 0x02130313, 0x0062c5b3, 0x0080006f, 0x00159593,
    0x000102b7, 0xfff28293, 0x0055f5b3, 0x00160613, 0xfc5ff06f, 0xfa1ff06f,
    0x00058513, 0x00008067, 0xff010113, 0x00112623, 0x00912423, 0x00001517,
    0xf7450513, 0x00000097, 0xf78080e7, 0x00050493, 0x000202b7, 0x0092a823,
    0x0ff4f293, 0x00020337, 0x00532023, 0x00000513, 0x00c12083, 0x00812483,
    0x01010113, 0x00008067,
]
CRC_DATA = b'123456789\x00'
SIEVE_O0 = [
    0x00000097, 0x00c080e7, 0x00100073, 0xfe010113, 0x00112e23, 0x00812c23,
    0x02010413, 0xfe042a23, 0x00200293, 0xfe542823, 0xff042283, 0x06400313,
    0x0862d663, 0x00001297, 0xfcc28293, 0xff042303, 0x006282b3, 0x0002c283,
    0x06029263, 0xff042283, 0x00020337, 0x00532823, 0xff442283, 0x00128293,
    0xfe542a23, 0xff042283, 0xff042303, 0x006282b3, 0xfe542623, 0xfec42283,
    0x06400313, 0x0262d863, 0x00100293, 0x00001317, 0xf7c30313, 0xfec42383,
    0x00730333, 0x00530023, 0xfec42283, 0xff042303, 0x006282b3, 0xfe542623,
    0xfcdff06f, 0xff042283, 0x00128293, 0xfe542823, 0xf71ff06f, 0xff442283,
    0x00020337, 0x00532823, 0x00000513, 0x01c12083, 0x01812403, 0x02010113,
    0x00008067,
]
SIEVE_O1 = [
    0x00000097, 0x00c080e7, 0x00100073, 0x00000513, 0x00200593, 0x06400293,
    0x0455da63, 0x00001297, 0xfe428293, 0x00b282b3, 0x0002c283, 0x02029c63,
    0x000202b7, 0x00b2a823, 0x00150513, 0x00b58633, 0x06400293, 0x02565063,
    0x00100293, 0x00001317, 0xfb430313, 0x00c30333, 0x00530023, 0x00b60633,
    0xfe1ff06f, 0x00158593, 0xfadff06f, 0x000202b7, 0x00a2a823, 0x00000513,
    0x00008067,
]
SIEVE_DATA = bytes(100)

LOADS_SET = {'lb', 'lh', 'lw', 'lbu', 'lhu'}
STORES_SET = {'sb', 'sh', 'sw'}

def profile(trace):
    # Count, over the trace: instructions, loads, stores, branches, taken (branches taken),
    # jumps (jal and jalr) and load_use (a load whose rd, not x0, is read as rs1 or rs2 by the
    # very next instruction). A five-stage pipeline takes one cycle per instruction, plus one
    # for each load-use stall and two for each taken branch or jump. Return a dict with those
    # counts, cycles and cpi (cycles per instruction).
    return {}
```

```python solution
MEM_SIZE = 0x30000
TEXT, DATA, STACK = 0x0, 0x1000, 0x10000

def sext(v, bits):
    # Sign-extend the low `bits` bits of v.
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

R_OPS = {(0, 0): 'add', (0, 0x20): 'sub', (1, 0): 'sll', (2, 0): 'slt', (3, 0): 'sltu',
         (4, 0): 'xor', (5, 0): 'srl', (5, 0x20): 'sra', (6, 0): 'or', (7, 0): 'and'}
I_OPS = {0: 'addi', 2: 'slti', 3: 'sltiu', 4: 'xori', 6: 'ori', 7: 'andi'}
LOADS = {0: 'lb', 1: 'lh', 2: 'lw', 4: 'lbu', 5: 'lhu'}
STORES = {0: 'sb', 1: 'sh', 2: 'sw'}
BRANCHES = {0: 'beq', 1: 'bne', 4: 'blt', 5: 'bge', 6: 'bltu', 7: 'bgeu'}

def decode(w):
    # One 32-bit instruction word to (name, rd, rs1, rs2, imm), with imm already sign-extended.
    op, rd, f3 = w & 0x7F, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op == 0x33:
        return R_OPS[(f3, f7)], rd, rs1, rs2, 0
    if op == 0x13:
        if f3 == 1:
            return 'slli', rd, rs1, 0, rs2
        if f3 == 5:
            return ('srai' if f7 else 'srli'), rd, rs1, 0, rs2
        return I_OPS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x03:
        return LOADS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x23:
        return STORES[f3], 0, rs1, rs2, sext((f7 << 5) | rd, 12)
    if op == 0x63:
        imm = ((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 63) << 5) | (((w >> 8) & 15) << 1)
        return BRANCHES[f3], 0, rs1, rs2, sext(imm, 13)
    if op == 0x37:
        return 'lui', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x17:
        return 'auipc', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x6F:
        imm = ((w >> 31) << 20) | (((w >> 12) & 255) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 1023) << 1)
        return 'jal', rd, 0, 0, sext(imm, 21)
    if op == 0x67:
        return 'jalr', rd, rs1, 0, sext(w >> 20, 12)
    if w == 0x00100073:
        return 'ebreak', 0, 0, 0, 0
    raise ValueError(f'unknown instruction {w:#010x}')

class CPU:
    def __init__(self, words, data=b''):
        self.mem = bytearray(MEM_SIZE)
        for k, w in enumerate(words):
            self.mem[TEXT + 4*k:TEXT + 4*k + 4] = (w & 0xFFFFFFFF).to_bytes(4, 'little')
        self.mem[DATA:DATA + len(data)] = bytes(data)
        self.x = [0]*32
        self.x[2] = STACK
        self.pc = TEXT
        self.count = 0

    def load(self, addr, n):
        return int.from_bytes(self.mem[addr:addr + n], 'little')

    def store(self, addr, n, value):
        self.mem[addr:addr + n] = (value & ((1 << 8*n) - 1)).to_bytes(n, 'little')

    def step(self):
        name, rd, rs1, rs2, imm = decode(self.load(self.pc, 4))
        a, b = self.x[rs1], self.x[rs2]
        u = lambda v: v & 0xFFFFFFFF
        nxt, val = self.pc + 4, None
        if name == 'ebreak':
            self.count += 1
            return False
        elif name == 'add': val = a + b
        elif name == 'sub': val = a - b
        elif name == 'and': val = a & b
        elif name == 'or': val = a | b
        elif name == 'xor': val = a ^ b
        elif name == 'sll': val = a << (b & 31)
        elif name == 'srl': val = u(a) >> (b & 31)
        elif name == 'sra': val = a >> (b & 31)
        elif name == 'slt': val = int(a < b)
        elif name == 'sltu': val = int(u(a) < u(b))
        elif name == 'addi': val = a + imm
        elif name == 'andi': val = a & imm
        elif name == 'ori': val = a | imm
        elif name == 'xori': val = a ^ imm
        elif name == 'slti': val = int(a < imm)
        elif name == 'sltiu': val = int(u(a) < u(imm))
        elif name == 'slli': val = a << imm
        elif name == 'srli': val = u(a) >> imm
        elif name == 'srai': val = a >> imm
        elif name == 'lui': val = imm
        elif name == 'auipc': val = self.pc + imm
        elif name in ('lb', 'lh', 'lw', 'lbu', 'lhu'):
            n = {'lb': 1, 'lh': 2, 'lw': 4, 'lbu': 1, 'lhu': 2}[name]
            val = self.load(u(a + imm), n)
            if name in ('lb', 'lh', 'lw'):
                val = sext(val, 8*n)
        elif name in ('sb', 'sh', 'sw'):
            self.store(u(a + imm), {'sb': 1, 'sh': 2, 'sw': 4}[name], b)
        elif name in ('beq', 'bne', 'blt', 'bge', 'bltu', 'bgeu'):
            taken = {'beq': a == b, 'bne': a != b, 'blt': a < b, 'bge': a >= b,
                     'bltu': u(a) < u(b), 'bgeu': u(a) >= u(b)}[name]
            if taken:
                nxt = self.pc + imm
        elif name == 'jal':
            val, nxt = self.pc + 4, self.pc + imm
        elif name == 'jalr':
            val, nxt = self.pc + 4, (a + imm) & ~1
        if val is not None and rd:
            self.x[rd] = sext(val, 32)
        self.pc = u(nxt)
        self.count += 1
        return True

    def run(self, limit=1000000):
        while self.count < limit and self.step():
            pass
        return self.count

def trace_program(words, data=b''):
    # Run a program on the core and record every instruction it executes as
    # (name, rd, rs1, rs2, taken), where taken says whether a branch went to its target.
    cpu, out = CPU(words, data), []
    while True:
        pc = cpu.pc
        name, rd, rs1, rs2, imm = decode(cpu.load(pc, 4))
        going = cpu.step()
        out.append((name, rd, rs1, rs2, name in BRANCHES.values() and cpu.pc != pc + 4))
        if not going:
            return out

# CRC-16 and the sieve compiled at -O0 and -O1.
CRC_O0 = [
    0x00000097, 0x0e0080e7, 0x00100073, 0xfe010113, 0x00112e23, 0x00812c23,
    0x02010413, 0xfea42a23, 0x000102b7, 0xfff28293, 0xfe542823, 0xff442283,
    0x0002c283, 0x08028c63, 0xff042283, 0xff442303, 0x00030393, 0x00130313,
    0xfe642a23, 0x0003c383, 0x00839393, 0x0072c2b3, 0xfe542823, 0xfe042623,
    0xfec42283, 0x00800313, 0x0662d063, 0xff042283, 0x00008337, 0x0062f2b3,
    0x02028063, 0xff042283, 0x00129293, 0x00001337, 0x02130313, 0x0062c2b3,
    0xfe542823, 0x0100006f, 0xff042283, 0x00129293, 0xfe542823, 0xff042283,
    0x00010337, 0xfff30313, 0x0062f2b3, 0xfe542823, 0xfec42283, 0x00128293,
    0xfe542623, 0xf9dff06f, 0xf65ff06f, 0xff042503, 0x01c12083, 0x01812403,
    0x02010113, 0x00008067, 0xff010113, 0x00112623, 0x00812423, 0x01010413,
    0x00001517, 0xf1050513, 0x00000097, 0xf14080e7, 0x00050293, 0xfe542a23,
    0xff442283, 0x00020337, 0x00532823, 0xff442283, 0x0ff2f293, 0x00020337,
    0x00532023, 0x00000513, 0x00c12083, 0x00812403, 0x01010113, 0x00008067,
]
CRC_O1 = [
    0x00000097, 0x080080e7, 0x00100073, 0x000105b7, 0xfff58593, 0x00054283,
    0x06028063, 0x00050293, 0x00150513, 0x0002c283, 0x00829293, 0x0055c5b3,
    0x00000613, 0x00800293, 0x02565e63, 0x000082b7, 0x0055f2b3, 0x00028c63,
    0x00159293, 0x00001337, 0x02130313, 0x0062c5b3, 0x0080006f, 0x00159593,
    0x000102b7, 0xfff28293, 0x0055f5b3, 0x00160613, 0xfc5ff06f, 0xfa1ff06f,
    0x00058513, 0x00008067, 0xff010113, 0x00112623, 0x00912423, 0x00001517,
    0xf7450513, 0x00000097, 0xf78080e7, 0x00050493, 0x000202b7, 0x0092a823,
    0x0ff4f293, 0x00020337, 0x00532023, 0x00000513, 0x00c12083, 0x00812483,
    0x01010113, 0x00008067,
]
CRC_DATA = b'123456789\x00'
SIEVE_O0 = [
    0x00000097, 0x00c080e7, 0x00100073, 0xfe010113, 0x00112e23, 0x00812c23,
    0x02010413, 0xfe042a23, 0x00200293, 0xfe542823, 0xff042283, 0x06400313,
    0x0862d663, 0x00001297, 0xfcc28293, 0xff042303, 0x006282b3, 0x0002c283,
    0x06029263, 0xff042283, 0x00020337, 0x00532823, 0xff442283, 0x00128293,
    0xfe542a23, 0xff042283, 0xff042303, 0x006282b3, 0xfe542623, 0xfec42283,
    0x06400313, 0x0262d863, 0x00100293, 0x00001317, 0xf7c30313, 0xfec42383,
    0x00730333, 0x00530023, 0xfec42283, 0xff042303, 0x006282b3, 0xfe542623,
    0xfcdff06f, 0xff042283, 0x00128293, 0xfe542823, 0xf71ff06f, 0xff442283,
    0x00020337, 0x00532823, 0x00000513, 0x01c12083, 0x01812403, 0x02010113,
    0x00008067,
]
SIEVE_O1 = [
    0x00000097, 0x00c080e7, 0x00100073, 0x00000513, 0x00200593, 0x06400293,
    0x0455da63, 0x00001297, 0xfe428293, 0x00b282b3, 0x0002c283, 0x02029c63,
    0x000202b7, 0x00b2a823, 0x00150513, 0x00b58633, 0x06400293, 0x02565063,
    0x00100293, 0x00001317, 0xfb430313, 0x00c30333, 0x00530023, 0x00b60633,
    0xfe1ff06f, 0x00158593, 0xfadff06f, 0x000202b7, 0x00a2a823, 0x00000513,
    0x00008067,
]
SIEVE_DATA = bytes(100)

LOADS_SET = {'lb', 'lh', 'lw', 'lbu', 'lhu'}
STORES_SET = {'sb', 'sh', 'sw'}

def profile(trace):
    p = dict(instructions=len(trace), loads=0, stores=0, branches=0, taken=0, jumps=0, load_use=0)
    for k, (name, rd, rs1, rs2, taken) in enumerate(trace):
        if name in LOADS_SET:
            p['loads'] += 1
            if rd and k + 1 < len(trace) and rd in trace[k + 1][2:4]:
                p['load_use'] += 1
        elif name in STORES_SET:
            p['stores'] += 1
        elif name in BRANCHES.values():
            p['branches'] += 1
            p['taken'] += taken
        elif name in ('jal', 'jalr'):
            p['jumps'] += 1
    p['cycles'] = p['instructions'] + p['load_use'] + 2*(p['taken'] + p['jumps'])
    p['cpi'] = p['cycles']/p['instructions']
    return p
```

```python tests
_tiny = [('lw', 5, 2, 0, False), ('add', 6, 5, 7, False), ('beq', 0, 6, 0, True), ('jal', 1, 0, 0, False), ('ebreak', 0, 0, 0, False)]
_p = profile(_tiny)
assert _p['load_use'] == 1 and _p['taken'] == 1 and _p['jumps'] == 1 and _p['cycles'] == 5 + 1 + 4, f"A load used at once stalls 1 cycle, and a taken branch and a jump cost 2 each: 10 cycles; got {_p.get('cycles')}."
_c1 = profile(trace_program(CRC_O1, CRC_DATA))
assert (_c1['instructions'], _c1['loads'], _c1['stores'], _c1['load_use']) == (1042, 21, 4, 19), f"CRC at -O1: 1042 instructions, 21 loads, 4 stores, 19 load-use stalls; got {_c1}."
assert (_c1['branches'], _c1['taken'], _c1['jumps'], _c1['cycles']) == (163, 51, 116, 1395), f"…163 branches (51 taken), 116 jumps, 1395 cycles; got {_c1}."
_c0 = profile(trace_program(CRC_O0, CRC_DATA))
assert _c0['cycles'] == 2203 and _c0['loads'] == 423, f"At -O0 the stack traffic adds loads (423) and stalls: 2203 cycles; got {_c0['cycles']}."
_s0, _s1 = profile(trace_program(SIEVE_O0, SIEVE_DATA)), profile(trace_program(SIEVE_O1, SIEVE_DATA))
assert (_s0['cycles'], _s1['cycles']) == (4954, 3123), f"The sieve takes 4954 cycles at -O0 and 3123 at -O1; got {_s0['cycles']} and {_s1['cycles']}."
assert abs(_c1['cpi'] - 1395/1042) < 1e-12, "CPI is cycles over instructions."
```

::: right
Right. Your profiler counts every stall and flush and reproduces the cycle counts for both programs at both optimization levels.
:::
:::

::: check
given: N = 1042 | 2339 | 3636; c = 1.2 | 1.34 | 1.5; f = 50 | 200 | 1000
answer: N*c/f
unit: µs
tolerance: 0.5%

## A program executes {N} instructions at a CPI of {c} on a {f} MHz clock. How long does it take?

::: right
Right. $N \times \text{CPI}/f$ = {answer} µs.
:::

::: misses
- [N/f] Include the CPI.
- [any] Not yet. The iron law.
:::
:::

::: check
given: N = 1000 | 2339; s = 19 | 98 | 183; b = 99 | 167 | 343
answer: (N + s + 2*b)/N
tolerance: 0.5%

## A trace has {N} instructions, {s} load-use stalls and {b} taken branches and jumps, which cost 2 cycles each. What's its CPI?

::: right
Right. ({N} + {s} + 2 × {b})/{N} = {answer}.
:::

::: misses
- [(N + s + b)/N] Each taken branch or jump costs two cycles.
- [any] Not yet. Total cycles over instructions.
:::
:::

::: check
given: a = 2203 | 3000 | 4954; b = 1000 | 1395
answer: a/b
tolerance: 0.5%

## A program takes {a} cycles unoptimized and {b} optimized. What's the speedup?

::: right
Right. {answer} times faster.
:::

::: misses
- [b/a] Speedup is the old time over the new.
- [any] Not yet. Old cycles over new.
:::
:::

::: check
kind: parts
given: s = 10 | 20 | 30; p = 1 | 2; b = 15 | 20; m = 10 | 30

## A five-stage pipeline stalls {p} cycle(s) on each load-use hazard, which follow {s}% of instructions, and loses 2 cycles on each mispredicted branch: branches are {b}% of instructions and {m}% of them mispredict.

::: part
answer: 1 + s/100*p + b/100*m/100*2
tolerance: 0.5%

### What is its CPI?

::: misses
- [1 + s/100*p + b/100*2] Only mispredicted branches cost cycles.
- [any] Not yet. $1 + \sum(\text{frequency} \times \text{penalty})$.
:::
:::

::: part
answer: 4.2/(1 + s/100*p + b/100*m/100*2)
tolerance: 0.5%

### Against a multicycle version averaging 4.2 cycles per instruction at the same clock, what's the speedup?

::: misses
- [5/(1 + s/100*p + b/100*m/100*2)] Compare with 4.2 cycles, not the number of stages.
- [any] Not yet. Ratio of CPIs.
:::
:::

::: right
Right. Hazards keep a pipeline from reaching its ideal CPI of 1.
:::
:::

::: check
given: t1 = 10 | 20; t2 = 2 | 4 | 6
answer: t1/t2
tolerance: 0.5%

## An optimized build runs a benchmark in {t2} ms against {t1} ms for the unoptimized one. What is the speedup?

::: right
Right: {answer}. Speedup is old time over new time.
:::

::: misses
- [t2/t1] Speedup is the old time divided by the new.
- [any] Not yet. $t_{old}/t_{new}$.
:::
:::

::: explain
## Why did the compiler's optimizer cut the CRC's loads twentyfold but leave its branch penalty untouched?

::: model
Without optimization, the compiler keeps every variable in its stack frame and loads it before each use and stores it after each change, so the loop's counters and the running CRC go through memory on every step. The optimizer keeps those variables in registers for the whole loop, which removes nearly all the loads and stores and the stalls that came with them. The branches and jumps implement the loops and the if-else, which the program needs at any optimization level, so the same number are taken and the pipeline pays the same flush penalty for each. Removing that cost takes hardware, a branch predictor, or a different algorithm with fewer branches.
:::
:::

::: practice

::: check
given: N = 500 | 1e6; c = 0.5 | 2.5; f = 10 | 3000
answer: N*c/f
unit: µs
tolerance: 0.5%

## Time: {N} instructions, CPI {c}, {f} MHz?

::: misses
- [any] $N \times \text{CPI}/f$.
:::
:::

::: check
given: N = 100 | 10000; s = 5 | 2000; b = 10 | 3000
answer: (N + s + 2*b)/N
tolerance: 0.5%

## CPI: {N} instructions, {s} stalls, {b} taken branches and jumps?

::: misses
- [any] $(N + s + 2b)/N$.
:::
:::
:::
