TactivergeOffline

Computer Architecture

Instruction sets, performance, hazards, caches, I/O, parallelism, energy and measurement: the quantitative view

Read Digital Logic and Computer Architecture first: it builds the gates, adders, state machines and first datapath this book takes for granted. Here the question changes from 'how does it work?' to 'how well, and at what cost?'. Eight chapters cover instruction-set trade-offs, the Iron Law, pipeline hazards, cache design, the hardware–software boundary, Amdahl's law and accelerators, energy and reduced precision, and benchmarking you can defend.

Version 1 · Technically checked (automated checks only) · 8 chapters · 64 practice questions (questions only)

Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.

1. Instruction-set design

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

An instruction set is a contract: software promises to use only these instructions, and hardware promises what each one does. Designing it is a game of trade-offs inside a fixed word. More registers mean fewer memory trips but smaller immediates; more opcodes mean richer instructions but fewer bits for operands. This chapter encodes instructions by hand, writes and times a small program, and meets the memory-mapped registers where software reaches the outside world.

Figure 1.1. Every bit is spent somewhere (described in words)

Two 16-bit instruction formats with a 4-bit opcode (16 opcodes). With 8 registers, rd and rs take 3 bits each and the immediate gets 6 bits, values 0 to 63. With 16 registers they take 4 bits each and the immediate shrinks to 4 bits, values 0 to 15.

Explanation

1.1 The contract between code and silicon

Code compiled years ago still runs on brand-new processors with completely different insides. What promise makes that possible?

What an ISA promises

An instruction set architecture defines: the registers visible to programs (Nibble has one, A, plus flags Z and C); the instructions and exactly what each does; their encoding as bits; how operands are found (addressing modes: a constant, a register, a memory address); and how memory and I/O look to software. Anything not in the contract is free for the hardware designer to change.

Architecture vs microarchitecture

Two chips implementing the same ISA can be utterly different inside: one takes 3 clock cycles per instruction, another overlaps many instructions in a pipeline. Both run the same program and get the same answers; only the speed differs. That separation is why software lasts longer than any one chip.

Design styles

Accumulator machines (like Nibble) keep one working register. Load–store / RISC machines (like RISC-V or the TV-16 teaching format) do arithmetic only between registers, with separate load and store instructions. CISC machines allow memory operands in arithmetic. Fewer, simpler instructions make hardware simpler; richer ones make programs shorter.

Common mix-ups

1.2 Instructions are just numbers

The hex number 0x1405 can be a price, a colour or an instruction that puts 5 into register 2. How does the processor know which?

Fields

An instruction word is divided into fields. TV-16 (a teaching format made for these lessons) uses 16 bits: opcode bits 15–12 (16 operations), rd bits 11–9 and rs bits 8–6 (registers R0–R7), and imm bits 5–0 (a constant 0–63). Nibble packs an opcode nibble and a 4-bit argument into 8 bits: word = opcode × 16 + arg.

Encoding and decoding

To encode, shift each field to its position and combine: word = opcode·2¹² + rd·2⁹ + rs·2⁶ + imm. LDI R2, 5 = 1·4096 + 2·512 + 0 + 5 = 5125 = 0x1405. To decode, shift right and mask: rd = (word >> 9) AND 7. In hardware, decoding is just wiring: each field's bits run straight to the circuits that need them.

Bits are a budget

Every field width is a trade-off. More opcode bits allow more instructions; more register bits allow more registers; more immediate bits allow bigger constants. A 16-bit word can't have all three. That is why real ISAs have several formats and why loading a large constant can take two instructions.

Common mix-ups

1.3 Project: program the processor

The Nibble machine can't multiply. By the end of this lesson it will, using only adding, storing and one conditional jump.

Plan with a loop invariant

Before coding, state what stays true each time round the loop, for example: 'M2 + x × (remaining y) = x × original y'. Each pass adds x to M2 and takes 1 off y; when y reaches 0 the invariant gives M2 = x × y. Invariants turn 'I think it works' into an argument.

Test the edges

Test small ordinary cases (3 × 4), the identities (1 × 7), and the zeros (0 × 6, 6 × 0). In 4 bits, results above 15 wrap, and a loop that counts y down with ADD 15 behaves surprisingly when y starts at 0: trace it and explain what happens. The build's own notes describe the behaviour you should be able to justify.

Measure, don't guess

Record instructions executed for several y and fit a formula: instructions = b·y + s, where b is the loop body length and s the setup and HALT. Multiply by cycles per instruction (3 in the stepper's model) for cycles. This table is your 'before' measurement for the speed-up.

Common mix-ups

1.4 Registers and bit masks: where software touches silicon

One line of C turns on a motor driver. Which single bit, at which address, did it change, and what else could it break?

Memory-mapped I/O

Microcontrollers give each peripheral (GPIO, timers, ADC, UART) a block of addresses. Writing to an address doesn't store data in RAM; it sets flip-flops whose outputs drive the hardware: a pin's direction, a timer's prescaler, an interrupt enable. Reading may return live hardware state, such as whether a conversion has finished.

The four mask operations

Set bit n: reg |= (1 << n). Clear: reg &= ~(1 << n). Toggle: reg ^= (1 << n). Test: (reg & (1 << n)) != 0. Multi-bit fields (a 3-bit prescaler at bits 4–6) are cleared with a field mask, then the new value is ORed in, shifted into place. Datasheets give each bit's meaning; the code should name them, not use magic numbers.

Read–modify–write hazards

reg |= mask is really three steps: read, OR, write. If an interrupt changes the same register between the read and the write, its change is lost. Fixes: disable interrupts briefly around the update, or use hardware 'set' and 'clear' registers that change only the bits you write as 1. Some status bits clear when read, so even reading has side effects.

Integration means checking both sides

A firmware unit test can't see a wrongly configured clock. Integration tests run real code on real (or accurately simulated) hardware and check observable behaviour: the pin toggles at the expected frequency, the ADC reads a known voltage correctly. Write down what each register should contain and check it in a debugger.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

The contract between code and silicon: example 1

Write a Nibble program that sets M3 to M0 + M0.

Instructions are just numbers: example 1

Decode TV-16 word 0x2280.

Project: program the processor: example 1

A different looping program's measured step counts are 14 for y = 2 and 26 for y = 4. Find b and s.

Registers and bit masks: where software touches silicon: example 1

reg = 0x5A (0101_1010). Clear bit 3, then toggle bit 0. Result?

Interactive figures, in words

Figure 1.2 from “Instructions are just numbers”

Encode LDI R2, 5 and ADD R1, R2, 0 and write down their hex words. Then type A2C3 into the decoder and explain each field. Finally switch to the Nibble format and encode LOAD 2: why is it 0x12?

The encoder shows each bit of the word coloured by field. LDI R2, 5 encodes to 0x1405; ADD R1, R2, 0 to 0x2280; 0xA2C3 decodes to opcode 10 (ADDI), rd = 1, rs = 3, imm = 3. In the Nibble format LOAD 2 is opcode 1 and argument 2, so 0x12 = 18.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Which of these is NOT part of an ISA?

  • The list of instructions
  • The number of programmer-visible registers
  • How many clock cycles the cache takes on a miss
  • How instructions are encoded in bits

Check it in “The contract between code and silicon”

2. Two processors implement the same ISA. One is three times faster. What can you say?

  • They must have identical circuits
  • The same program gives the same results on both; only timing differs
  • Programs must be rewritten for the faster one
  • The faster one must have more instructions

Check it in “The contract between code and silicon”

3. TV-16's immediate field is 6 bits, unsigned. What is the largest constant LDI can load in one instruction?

Answer:

Check it in “Instructions are just numbers”

4. A designer wants 16 registers instead of 8 in TV-16, keeping 16-bit words and two register fields. What must shrink?

  • Nothing
  • The opcode or immediate fields lose 2 bits in total
  • The word must become 15 bits
  • The registers must become smaller

Check it in “Instructions are just numbers”

5. Why state a loop invariant before writing the program?

  • It makes the program run faster
  • It gives a reason the result is right when the loop ends, not just a hope
  • The assembler requires it
  • It replaces testing

Check it in “Project: program the processor”

6. reg = 0x3C. After reg |= 0x81, what is reg in decimal?

Answer:

Check it in “Registers and bit masks: where software touches silicon”

7. A 3-bit prescaler field sits at bits 4–6 of an 8-bit register that currently holds 0x0F. You write the value 5 into the field. What does the register hold now, in decimal?

Answer:

Check it in “Registers and bit masks: where software touches silicon”

8. Main code does PORT |= LED_BIT while an interrupt handler sets MOTOR_BIT in the same register. Occasionally the motor bit is lost. Why?

  • The compiler is broken
  • The interrupt ran between main's read and write, so main wrote back the old value
  • Bits can't be shared
  • The LED draws too much current

Check it in “Registers and bit masks: where software touches silicon”

Engineering applications

Compressed instructions

Some instruction sets add a 16-bit form of the most common 32-bit instructions. Code shrinks by about a quarter, which matters when the program must fit in a small microcontroller's flash.

Peripheral registers

A timer's prescaler, mode and enable bits share one register. Firmware changes one field with a read, mask and write, and must stop an interrupt from changing the same register halfway through.

Summary

Glossary

Instruction set architecture (ISA)
The ISA is the contract between software and hardware: the instructions, registers, data types and addressing modes a processor promises to support.
Registers
Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
Fetch–decode–execute cycle
A processor runs a program by repeatedly fetching the instruction at the program counter, decoding what it means, executing it and moving the program counter on.
Memory-mapped I/O
With memory-mapped I/O, peripheral control and data registers appear at fixed memory addresses, so the processor talks to hardware with ordinary load and store instructions.
Hexadecimal
Hexadecimal is base 16, using digits 0–9 and A–F. Each hex digit stands for exactly four bits, so two hex digits describe one byte.

Project: Design a 16-bit instruction format

Design an instruction format for a small controller with at least 12 operations. Choose the field widths, justify the register count, and encode a five-instruction program by hand. State one program your format makes awkward.

Deliverables

  • The format diagram with field widths
  • The encoded program in binary and hexadecimal
  • A trade-off note: what you gave up and why

References

2. The performance equation

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Execution time is instructions × cycles per instruction × seconds per cycle. That one line, the Iron Law, keeps every performance argument honest. A faster clock means little if each instruction needs more cycles; a clever instruction means little if the clock must slow to fit it. This chapter finds the clock period from the critical path, compares single-cycle and multi-cycle datapaths, and budgets cycles for a real-time signal loop.

Figure 2.1. The clock is not the whole story (described in words)

Two designs run the same one billion instructions. Design A has CPI 1.2 at 2.5 GHz and takes 0.48 s. Design B has a lower CPI of 0.9 but a slower 1.8 GHz clock and takes 0.5 s. Neither the clock rate nor the CPI alone decides which is faster.

Explanation

2.1 How fast can the clock tick?

Why can't a processor designer just set the clock to 100 GHz and make everything 25 times faster?

The critical path

Every path from a register output through gates to a register input must settle within one clock period. The longest one sets the clock. In a ripple-carry adder it is the carry rippling through every column: about 2 gate delays per bit, so a 32-bit ripple adder is roughly eight times slower than a 4-bit one.

Shortening it

Designers attack the critical path with faster circuits (carry-lookahead adders compute carries in parallel at the cost of more gates), or by pipelining: putting registers in the middle of a long path so each piece fits a shorter period. The clock speeds up; each operation now takes more cycles, but a new one can start every cycle.

More cycles or faster cycles?

Run time = cycles × T_clk. A single-cycle design does everything in one long cycle; a multi-cycle design (like the 3-step model in the stepper) uses several short ones. Which wins depends on how evenly the work splits: the iron law T = IC × CPI × T_clk keeps every trade-off honest.

Derivation: The register-to-register timing constraint
  1. At a clock edge the launching register's output changes after t_clk→Q.

  2. The new value travels through combinational logic; the slowest route, the critical path, takes t_logic.

  3. The capturing register needs its input stable for t_setup before the next edge.

  4. So the next edge must come no sooner than T_clk ≥ t_clk→Q + t_logic + t_setup, and f_max = 1/T_clk.

  5. Example: 0.2 + 10 × 0.1 + 0.1 = 1.3 ns, so f_max = 1/1.3 ns ≈ 769 MHz.

Common mix-ups

2.2 Single-cycle, multi-cycle and the Iron Law

Chip A runs at 4 GHz, chip B at 2 GHz. B finishes your program first. How?

Single-cycle datapath

Every instruction completes in one long clock cycle, so CPI = 1, but the cycle must be long enough for the slowest path (instruction memory → register read → ALU → data memory → register write, for a load). Simple instructions waste most of the cycle.

Multi-cycle datapath

Break execution into steps (fetch, decode, execute, memory, write-back) and give each step one short cycle. Instructions use only the steps they need, so CPI is now an average (perhaps 4) but the cycle is about the length of one step. Hardware can be reused across steps: one memory and one ALU instead of separate ones.

Three factors, coupled

A richer instruction set lowers IC but may raise CPI or the cycle time. A deeper pipeline shortens the cycle but raises CPI when hazards hit. A good comparison quotes all three and measures them on the same program, compiled the same way, which is why benchmark suites exist.

Derivation: The Iron Law, from units
  1. Time per program = (instructions / program) × (cycles / instruction) × (seconds / cycle).

  2. The units cancel: instructions × cycles/instruction × seconds/cycle = seconds. So T = IC × CPI × t_clk = IC × CPI / f.

  3. IC is set by the algorithm, the compiler and the instruction set. CPI by the microarchitecture (pipelining, caches, prediction). t_clk by the circuit and the process technology.

  4. Speed-up of B over A = T_A / T_B = (IC_A/IC_B) × (CPI_A/CPI_B) × (f_B/f_A).

  5. Example: A has IC = 10⁹, CPI = 2, 4 GHz: T = 0.5 s. B has IC = 0.8×10⁹, CPI = 1.1, 2 GHz: T = 0.44 s. B wins by 0.5/0.44 ≈ 1.14× despite half the clock.

Common mix-ups

2.3 Signals meet hardware: the cycle budget

A 48 MHz microcontroller sounds fast. Can it filter a 48 kHz audio signal in real time? It depends on one division.

The pipeline

Sensor → analog anti-aliasing filter → ADC (sample rate fs, N bits) → digital filter → decision or output. Each stage has a requirement from this term: fs > 2 × the highest wanted frequency with margin; N bits for the SNR you need; a filter whose response keeps the band and rejects noise; and a processor that keeps up.

The cycle budget

Cycles available per sample = f_clk / fs. Processor load = fs × (cycles per sample) / f_clk. Keep it well under 100 %, because interrupts, communication and the rest of the program need cycles too. A first-order IIR needs about two multiplies and an add per sample; an M-point moving average can be done with a running sum in constant time.

Trading between stages

A better analog filter lets you sample more slowly, saving cycles. More bits cost ADC time and memory but not filter cycles. An IIR filter gives strong smoothing for a handful of cycles but with phase lag; a long FIR filter has linear phase but costs a multiply per tap. Systems engineering is choosing these together, not one at a time.

Common mix-ups

2.4 Time, memory, accuracy: pick your trade

Halve the step size and the answer gets better. Halve it again and it gets slower. When do you stop?

Order of accuracy

A method of order p has global error ≈ C·h^p. Halving h divides the error by 2^p and doubles the work. Plot error against h on log–log axes: the slope is p, which is a powerful check that your code is correct. Below some h, rounding error in each step starts to accumulate and the curve turns back up.

Growth rates

An O(n) algorithm on a million items does about a million operations; O(n log n) about twenty million; O(n²) a trillion. For small n, a simple O(n²) method may be faster and far easier to verify. Choose by the sizes you actually face, measured, and by the cost of getting it wrong.

Memory as a resource

Storing results can save time (a lookup table replaces a slow sin(x)) at the cost of memory, and the table's spacing sets its accuracy. A microcontroller with 32 KB of RAM can't hold a 64 K-entry table, so you interpolate a smaller one. This is time versus memory versus accuracy in one decision.

Fixed point: precision you can count

Fixed-point stores x as an integer X = round(x·2^f) with f fractional bits. Resolution is 2^−f; rounding error is at most half of that per operation. Q8 (f = 8) resolves 1/256 ≈ 0.0039. It is fast and predictable on chips without a floating-point unit, but you must check the range (overflow) and the accumulated rounding in long loops.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

How fast can the clock tick?: example 1

A 16-bit ripple adder has 2 gate delays per bit plus 1, at 0.08 ns each, between registers with t_cq = 0.15 ns and t_su = 0.1 ns. Find f_max.

Single-cycle, multi-cycle and the Iron Law: example 1

A mix is 50% ALU (4 steps), 20% loads (5), 10% stores (4), 20% branches (3). Step time 200 ps. Compare with an 800 ps single-cycle design.

Signals meet hardware: the cycle budget: example 1

An 80 MHz processor filters a 44.1 kHz signal with a 128-tap FIR at 3 cycles per tap plus 100 cycles of overhead. What is the load?

Time, memory, accuracy: pick your trade: example 1

Euler gives error 0.32 at h = 0.4 and 0.16 at h = 0.2. Estimate p, then predict the error at h = 0.05.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. What sets the maximum clock frequency of a synchronous design?

  • The shortest register-to-register path
  • The longest register-to-register path (the critical path)
  • The number of registers
  • The supply voltage only

Check it in “How fast can the clock tick?”

2. Adding a pipeline register halfway along the critical path usually…

  • Halves the clock frequency
  • Allows a faster clock but makes each operation take one more cycle
  • Removes the need for a clock
  • Has no effect

Check it in “How fast can the clock tick?”

3. A compiler optimisation removes redundant instructions without changing the hardware. Which Iron Law factor does it change most directly?

  • Instruction count
  • Cycle time
  • Clock frequency
  • None

Check it in “Single-cycle, multi-cycle and the Iron Law”

4. Design A: CPI 1.6 at 3 GHz. Design B: CPI 1.0 at 2.4 GHz, same instruction count. What is B's speed-up over A?

Answer: ×

Check it in “Single-cycle, multi-cycle and the Iron Law”

5. A 16 MHz microcontroller samples at 8 kHz. How many clock cycles are available per sample?

Answer: cycles

Check it in “Signals meet hardware: the cycle budget”

6. A system is at 95 % load. Which change reduces load WITHOUT reducing the frequencies you can capture?

  • Halve the sample rate
  • Replace a long FIR filter with a first-order IIR that meets the smoothing requirement
  • Use fewer ADC bits
  • Lower the clock frequency

Check it in “Signals meet hardware: the cycle budget”

7. A sensor value is stored in Q8 fixed point (8 fractional bits). What is the largest possible rounding error for one stored value?

Answer:

Check it in “Time, memory, accuracy: pick your trade”

8. You sort 40 sensor readings once per second on a microcontroller. Is a simple O(n²) insertion sort acceptable?

  • No: O(n²) is always too slow
  • Yes: 40² = 1,600 comparisons is tiny, and simpler code is easier to verify
  • Only if n is exactly 40
  • Sorting is never needed

Check it in “Time, memory, accuracy: pick your trade”

Engineering applications

Choosing a microcontroller

For a control loop at 8 kHz, divide the clock rate by the sample rate to get the cycle budget per sample. That number, not the clock rate on the box, says whether the filter will fit.

Compiler flags

An optimising compiler mostly cuts instruction count; some options trade more instructions for fewer stalls. The Iron Law explains why a 'bigger' program can run faster.

Summary

Glossary

Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.
Propagation delay
Propagation delay is the time a gate's output takes to respond to a change at its input. The slowest path between flip-flops, the critical path, sets the fastest safe clock.
D flip-flop
A D flip-flop stores one bit. On each rising clock edge it copies its D input to its Q output and holds that value until the next edge.
Word size
A processor's word size is the number of bits it naturally handles in one operation: its register width and usually its main data path.

Project: Does the filter fit?

A sensor is sampled at a rate you choose between 1 and 20 kHz. Estimate the instruction count of a 16-tap filter, assume a CPI with stated reasons, and find the slowest clock that leaves 30 % headroom. Show the Iron Law calculation.

Deliverables

  • Instruction-count estimate with assumptions
  • Cycle budget per sample and headroom
  • The chosen clock with a one-paragraph argument

References

3. Pipelining and hazards

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A pipeline overlaps instructions like an assembly line, so in the ideal case one finishes every cycle. Reality interrupts. An instruction needs a value that is not ready yet (a data hazard), the next instruction depends on a branch not yet decided (a control hazard), or two stages want the same hardware (a structural hazard). This chapter counts the cost of each, shows how forwarding and prediction recover most of it, and explains measured speed-ups from first principles.

Figure 3.1. A load-use stall (described in words)

Three instructions in a five-stage pipeline. A load is followed by an add that uses the loaded register; even with forwarding the add waits one bubble for MEM to finish, so 3 instructions take 8 cycles instead of 7. With 0.25 loads per instruction, 0.4 of them used next, CPI becomes 1.1.

Explanation

3.1 Pipelining: an assembly line for instructions

A laundry takes 30 minutes to wash, 40 to dry and 20 to fold. How long do four loads take if you never wait for one to finish before starting the next?

Throughput versus latency

Pipelining does not make one instruction faster: it still passes through every stage, and register overhead makes it slightly slower. What improves is throughput: once full, the pipeline completes one instruction every cycle. Ideal CPI approaches 1 for long runs.

The classic five stages

IF fetches the instruction, ID decodes it and reads registers, EX uses the ALU, MEM accesses data memory, WB writes the result back. Registers between stages hold each instruction's state so the stages can work on different instructions at once.

Balance and overhead

The clock must suit the slowest stage, and every stage boundary adds a register's setup and clock-to-output delay. Deeper pipelines get diminishing returns and, as you will see, pay more for every hazard. Modern designs settle on roughly 10–20 stages as a compromise.

Derivation: How much faster can a pipeline be?
  1. Unpipelined: each instruction takes T, so n instructions take n·T.

  2. Split into k stages. If perfectly balanced, each stage is T/k, but each needs a pipeline register adding overhead o. Cycle = T/k + o.

  3. Pipelined time for n instructions = (k + n − 1)(T/k + o).

  4. Speed-up S = n·T / ((k + n − 1)(T/k + o)). As n → ∞, S → T/(T/k + o) = k / (1 + k·o/T).

  5. With no overhead the limit is k. With o = 0.1 T, a 5-stage pipe tops out at 5/1.5 ≈ 3.3×; a 20-stage pipe at 20/3 ≈ 6.7×, not 20×.

  6. Unbalanced stages are worse: the cycle is set by the slowest stage, so S ≤ T / max(stage delay).

Common mix-ups

3.2 Hazards, forwarding and branch prediction

An instruction needs a number the previous one hasn't finished computing. Does the whole assembly line stop?

Data hazards

A read-after-write hazard occurs when an instruction needs a register that an earlier, still-in-flight instruction will write. Without help, the reader stalls in ID until the writer reaches WB: 2 bubbles for adjacent instructions in the classic 5-stage pipe. Forwarding (bypassing) wires the ALU output straight back to the ALU input, removing the stall for ALU results.

The load-use stall

A load's data appears only at the end of MEM. Even with forwarding, an instruction that uses it immediately must wait one cycle. Compilers hide this by scheduling an independent instruction between the load and its use, which is why the 'Load then use' program in the pipeline diagram has an unrelated sub in the middle.

Control and structural hazards

A branch is not resolved until EX, so the pipeline has already fetched 2 instructions that may be wrong. Stalling on every branch wastes those cycles always; predict not taken wastes them only when the branch is taken; dynamic predictors learn each branch's habit and are right well over 90% of the time on typical code. A structural hazard arises when two stages need one resource, like a single memory port for fetch and data: hence separate instruction and data caches.

Hazards in the Iron Law

Every stall adds to CPI: CPI = 1 + (data stalls per instruction) + (branch fraction × mispredict rate × penalty) + (memory stalls). Deeper pipelines raise the branch penalty, so a faster clock can lose to a shorter pipe with a better predictor.

Common mix-ups

3.3 Explaining results from first principles

Your 8-bit version runs 2.6× faster than float, but the arithmetic is only 2× cheaper. Where did the rest come from?

Explain the numbers

For each metric, give the mechanism and check the size: operation counts for compute, bytes and AMAT for memory, quantisation step for accuracy, P = αCV²f and duty cycle for energy. A mechanism that predicts the right size of effect is far stronger than one that only predicts its direction.

Results that resist explanation

If the model leaves a gap, report it as an open question rather than stretching the explanation. 'The model predicts 2.75× but we measured 3.4×; we suspect hardware prefetching, which our model omits' is honest and useful.

The final report

Question and prediction; method (as pre-registered, with any deviations); results with uncertainty; first-principles explanation; recommendation from the pre-stated rule; limitations: simulation versus hardware, one workload, one compiler, toy data. No claim beyond the evidence.

Derivation: Decomposing a speed-up
  1. T = IC × CPI × t_clk, with CPI = CPI_base + (memory accesses per instruction) × miss rate × miss penalty.

  2. Speed-up S = T_A/T_B = (IC_A/IC_B) × (CPI_A/CPI_B) × (t_A/t_B). Taking logs, ln S = ln(IC ratio) + ln(CPI ratio) + ln(clock ratio): each factor's share adds.

  3. Example: SIMD packing halves IC (ratio 2). Smaller data cuts the miss rate from 6% to 3% with 0.4 accesses per instruction and a 50-cycle penalty: CPI 1 + 1.2 = 2.2 → 1 + 0.6 = 1.6 (ratio 1.375). Clock unchanged.

  4. Predicted S = 2 × 1.375 = 2.75×. If you measured 2.6× ± 0.1, the model explains it within uncertainty; the shares are ln 2 / ln 2.75 ≈ 68% from IC and 32% from CPI.

  5. If the model and measurement disagree beyond uncertainty, something unmodelled matters (branch behaviour, prefetching, frequency scaling): say so and investigate.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Pipelining: an assembly line for instructions: example 1

Stages of 200, 150, 250, 300 and 100 ps, register overhead 20 ps. Find the cycle time and the speed-up for many instructions versus the 1000 ps unpipelined design.

Hazards, forwarding and branch prediction: example 1

lw r1, 0(r2) then add r3, r1, r4, with forwarding. Stalls?

Hazards, forwarding and branch prediction: example 2

Branches are 15% of instructions; a predictor is wrong 8% of the time; the penalty is 3 cycles. Extra CPI?

Explaining results from first principles: example 1

Float: IC 10⁹, CPI 1.8, 1 GHz. Int8: IC 0.3×10⁹, CPI 2.1, 1 GHz. Speed-up and its sources?

Interactive figures, in words

Figure 3.2 from “Pipelining: an assembly line for instructions”

Choose 'Independent ALU ops', turn forwarding on and choose 'Perfect predictor'. Read the diagonal staircase and check the cycle count against k + n − 1. Then pick the other programs to see the ideal break: that is next lesson's topic.

The pipeline table has one row per instruction and one column per clock cycle; each instruction's IF, ID, EX, MEM and WB cells shift one column to the right of the previous instruction's, forming a staircase. For 5 independent instructions it ends at cycle 9.

Figure 3.3 from “Hazards, forwarding and branch prediction”

Every stall cycle adds to CPI, and this calculator shows how much. Set branches to 20%, mispredict to 10% and penalty to 2: read the CPI. Raise the penalty to 15 (a deep pipeline) and watch the branch slice grow. Pin a design, then trade a faster clock for a bigger penalty and read the speed-up.

The Iron Law calculator shows CPI as base + branch stalls + memory stalls. With 20% branches, 10% mispredicted at 2 cycles, and 30% memory instructions missing 5% at 40 cycles, CPI = 1 + 0.04 + 0.6 = 1.64, and T = IC × CPI ÷ f.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Compared with the unpipelined design, the latency of a single instruction in a pipeline is…

  • k times shorter
  • About the same or slightly longer
  • Always exactly one cycle
  • Zero once the pipeline is full

Check it in “Pipelining: an assembly line for instructions”

2. A 1,200 ps datapath is split into 6 perfectly balanced stages with 50 ps register overhead each. What is the speed-up limit for very long programs?

Answer: ×

Check it in “Pipelining: an assembly line for instructions”

3. lw r5, 4(r2) / add r6, r5, r1. Which hazard and, with forwarding, how many stall cycles?

  • Structural, 0
  • Data (load-use), 1
  • Control, 2
  • Data, 0 thanks to forwarding

Check it in “Hazards, forwarding and branch prediction”

4. Design B doubles the pipeline depth of A, raising the clock 1.6× and the branch penalty from 2 to 5 cycles. Branch fraction 20%, mispredict 10%, base CPI 1 for both, memory ignored. Which is faster?

  • A
  • B
  • Equal
  • Cannot tell without IC

Check it in “Hazards, forwarding and branch prediction”

5. On the classic 5-stage pipeline with no forwarding, a chain of 4 ALU instructions each uses the previous one's result. How many total cycles? (Ideal is 8.)

Answer: cycles

Check it in “Hazards, forwarding and branch prediction”

6. Why do most processors have separate L1 instruction and data caches?

  • To store more data
  • To remove the structural hazard of fetch and load/store needing memory in the same cycle
  • Because instructions are larger than data
  • To make branch prediction possible

Check it in “Hazards, forwarding and branch prediction”

7. Version B executes 0.5× the instructions of A, and its CPI falls from 2.0 to 1.5. Same clock. What speed-up does the Iron Law predict?

Answer: ×

Check it in “Explaining results from first principles”

8. Your model predicts 2.0× and you measured 2.9× ± 0.2. What should the report say?

  • Adjust the model until it gives 2.9×
  • The model explains part of the gain; the remaining gap is unexplained, with candidate causes and a test to check them
  • Drop the measurement
  • Claim the model is confirmed

Check it in “Explaining results from first principles”

Engineering applications

Instruction scheduling

Compilers move independent instructions into the slot after a load so the pipeline has useful work while the value arrives. The program means the same but runs in fewer cycles.

Branch-heavy code

Parsing and decision code branches unpredictably, so deeper pipelines lose more per mispredict. Predictable loops are why signal-processing code pipelines so well.

Summary

Glossary

Pipelining
Pipelining splits instruction execution into stages and overlaps them, so that while one instruction executes the next is being decoded and the one after is being fetched.
Pipeline hazards and forwarding
A hazard is a situation where the next instruction cannot proceed on schedule. Data hazards happen when an instruction needs a result an earlier one has not finished producing.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.

Project: Explain a speed-up

Using the pipeline simulation, measure CPI for a program mix with and without forwarding. Predict the speed-up from a stall model before running, then compare. Where they disagree by more than 10 %, find the cause.

Deliverables

  • The stall model with its assumptions
  • Predicted and measured CPI with a comparison
  • An explanation of any mismatch

References

4. Caches and the memory hierarchy

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

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

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

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

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

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

Examples to try

Worked solutions are in the interactive chapter online.

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?

Inside a cache: tags, sets and ways: example 1

A 32 KB direct-mapped cache, 64 B blocks, 32-bit addresses. Split the address.

Inside a cache: tags, sets and ways: example 2

Same cache made 2-way. What changes?

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?

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?

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.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?

  • Temporal
  • Spatial only
  • Neither
  • Only compulsory misses

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

  • Misses halve
  • Still 100% misses
  • No misses
  • Misses double

Check it in “Locality and the memory hierarchy”

3. Going from direct-mapped to 4-way set-associative at the same capacity mainly costs…

  • More tag comparators and a way multiplexer
  • More capacity
  • Smaller blocks
  • Nothing: it is free

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

  • Only the second A
  • The second A and the last B
  • None
  • All after the first two

Check 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: %

Check it in “Average memory access time”

6. AMAT = 1 + 0.08 × 50. Which single change helps most?

  • Cut hit time from 1 to 0.5 cycles
  • Cut miss rate from 8% to 6%
  • Cut miss penalty from 50 to 45 cycles
  • All save the same

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

Check 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: ms

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

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

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

  • Predicted and simulated hit rates in a table
  • AMAT for each configuration
  • A recommendation weighing speed against area

References

5. Input, output and the hardware–software boundary

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A processor is only useful when it talks to the world. This chapter follows bytes across the boundary: serial frames on a UART wire, full-duplex transfers on SPI, the choice between polling a device and letting it interrupt you, and the tool chain that turns source code into an image at fixed addresses. Each choice trades latency, throughput, energy and the risk of subtle bugs where software meets hardware.

Figure 5.1. One byte on a UART wire (described in words)

A UART 8N1 frame for the byte 0x4B (0100 1011). The idle-high line drops for the start bit, then carries data bits 1 1 0 1 0 0 1 0, least significant first, then a stop bit of 1. With 10 bits per byte, 115200 baud moves 11520 bytes per second.

Explanation

5.1 UART: one wire, ten bits, one byte

There is no clock wire between your laptop and a GPS module, yet not a single bit gets lost. How does the receiver know when each bit starts?

Asynchronous means no shared clock

A UART line rests high (idle). To send a byte, the transmitter pulls it low for one bit time: the start bit. The receiver sees that falling edge, waits half a bit, then samples once per bit time. Both sides must agree on the baud rate in advance; each keeps its own clock, so they only have to stay in step for one short frame before the next start bit lines them up again.

The frame, bit by bit

After the start bit come 8 data bits, least significant bit first, then an optional parity bit, then a stop bit (high) that returns the line to idle. The common format 8N1 means 8 data bits, no parity, 1 stop bit: 10 bits on the wire per byte. 8E1 adds an even-parity bit (11 bits). The letter A is 0x41 = 01000001, so the data bits go out as 1 0 0 0 0 0 1 0.

Parity: a one-bit alarm

With even parity the transmitter picks the parity bit so the total number of 1s in data + parity is even. 0x41 has two 1s, so its even-parity bit is 0. If noise flips any single bit, the count becomes odd and the receiver flags the frame. Two flipped bits cancel out and slip through, so parity detects errors but cannot correct them; real protocols add checksums on top.

When the text turns to garbage

A baud-rate mismatch makes the receiver sample in the wrong places, so bytes decode as nonsense or framing errors (no high stop bit where one was expected). Other usual suspects: transmit wired to transmit instead of crossing TX→RX, no shared ground, or a 5 V device talking to a 3.3 V input. UART voltage levels are a separate choice from the frame format.

Derivation: From baud rate to bytes per second
  1. One bit lasts T = 1/baud seconds. At 9600 baud, T = 1/9600 s ≈ 104.2 µs.

  2. One 8N1 frame is 1 start + 8 data + 1 stop = 10 bits, so it lasts 10·T ≈ 1.042 ms.

  3. Back to back with no idle gaps, frames per second = 1/(10·T) = baud/10 = 960.

  4. Each frame carries one data byte, so the maximum data rate is 960 bytes/s. In general: bytes/s = baud ÷ (bits per frame).

Common mix-ups

5.2 SPI: swapping bytes at full speed

A tiny colour screen needs over a megabyte every second. Which bus can keep up, and why does reading from it mean sending something too?

Four wires, one conversation at a time

SCLK is the clock from the controller. MOSI (controller out, peripheral in) and MISO (controller in, peripheral out) carry data. CS (chip select, active low) picks which peripheral is listening: each peripheral normally gets its own CS line, so four devices need four CS pins. There are no addresses: pulling a CS low is the address.

Two shift registers in a ring

Inside, the controller and the peripheral each hold an 8-bit shift register, joined in a ring by MOSI and MISO. On each clock, each side shifts its most significant bit out and takes the other side's bit in. After 8 clocks the bytes have swapped. That is why SPI is full duplex, and why reading always means writing something.

Modes: when to sample

Devices differ on the clock's idle level (CPOL) and on which edge data is sampled (CPHA), giving modes 0–3. Mode 0 (clock idles low, sample on the rising edge) is the most common. Controller and peripheral must use the same mode, or every bit is read half a clock off. The datasheet always states it; check it before blaming the wiring.

Choosing a bus

UART: 2 wires, point to point, no clock; 115200 baud 8N1 is about 11.5 kB/s. I²C: 2 wires shared by many addressed devices, acknowledged; 400 kHz gives at most about 44 kB/s before addressing overhead. SPI: 3 wires plus a CS per device, no addressing or acknowledge; 10 MHz moves 1.25 MB/s. Choose by data rate, number of devices and spare pins.

Derivation: SPI burst time and data rate
  1. SPI moves one bit per clock edge pair and has no start, stop, parity or acknowledge bits.

  2. So N bytes need exactly 8N clocks (with CS held low and no gaps).

  3. One clock lasts 1/f, so the burst takes t = 8N/f. With f in MHz, t comes out in microseconds.

  4. The maximum data rate is N/t = f/8 bytes per second: 8 MHz → 1 000 000 bytes/s.

Common mix-ups

5.3 Polling or interrupts? Latency, energy and shared data

Checking a button a million times a second never misses a press. Why is it usually the wrong design?

Polling

The main loop repeatedly reads a status bit. Simple, deterministic and easy to debug. Worst-case latency is the loop period (plus the work done each loop). Energy cost: the CPU wakes every period whether or not anything happened. Good when events are frequent and regular, or when you need a fixed sampling rate anyway (a control loop at 1 kHz).

Interrupts

Hardware detects the event and forces the CPU to run a short handler (an ISR). Latency is microseconds (entry cycles plus any time interrupts are disabled). Between events the CPU can sleep. The price is complexity: handlers interrupt main code at unpredictable moments, which creates races on shared data.

Protecting shared data

Rules of thumb: keep ISRs short (set a flag, copy a value, leave); declare shared variables volatile; read multi-byte values with interrupts briefly disabled or with a consistency check; use a ring buffer with one writer and one reader. Never call slow or blocking functions inside an ISR.

Hybrid designs

Many systems use an interrupt to wake from sleep, then poll briefly while active, or a timer interrupt that runs a fixed-rate control loop. The choice is a budget trade: latency target, energy per event, CPU time left for other work, and how much complexity you can verify.

Common mix-ups

5.4 From source code to running hardware, and testing the join

The code compiled, the tests passed, and the robot still twitched. Where in the chain did it go wrong?

The chain

Compiler: C or Rust → assembly for the target. Assembler: assembly → machine-code object files. Linker: combines objects and libraries, places code and data at real addresses using a linker script (flash here, RAM there). Image: a binary or hex file. Flashing: a programmer writes it into the chip's flash. Boot: the reset vector jumps to start-up code that sets up the stack and memory, then calls main.

Optimisation levels are trade-offs

-O0: slow, large, every variable visible to the debugger. -O2: fast, usually smaller. -Os: smallest. -O3: aggressive inlining, can be larger. On a microcontroller with 64 KB of flash, size may decide. Benchmark the configuration you will ship: timings measured on a debug build can differ greatly.

What changes between builds

Library versions, compiler versions, flags, linker scripts and configuration headers can all change behaviour. Reproducible builds pin them all and record a version or commit hash in the firmware itself, so a measurement can always be traced to the exact binary that produced it.

Integration testing

Unit tests check functions in isolation on a computer. Hardware-in-the-loop tests run the real firmware on the real board while a test rig feeds sensor signals and measures outputs and timing. Test the joins: clock configuration, interrupt latency under load, behaviour at power-up, and what happens when a sensor is unplugged.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

UART: one wire, ten bits, one byte: example 1

A logic analyser shows, after the start bit, the data bits 0 0 1 0 1 1 0 0 (first to last). What byte is it?

UART: one wire, ten bits, one byte: example 2

How long does one 8E1 frame take at 115200 baud?

SPI: swapping bytes at full speed: example 1

How long does it take to send 64 bytes to an SD card at 4 MHz?

SPI: swapping bytes at full speed: example 2

A board has 3 SPI peripherals and 1 I²C sensor. How many microcontroller pins do the buses use?

Polling or interrupts? Latency, energy and shared data: example 1

A polling loop runs every 2 ms and takes 0.3 ms per pass. What is the worst-case delay before an event is noticed?

From source code to running hardware, and testing the join: example 1

A firmware image is 58 KB at -O2 and 49 KB at -Os on a chip with 64 KB flash. The -Os build runs a control loop 12% slower. The loop has 30% timing margin. Which do you ship, and what do you record?

Interactive figures, in words

Figure 5.2 from “UART: one wire, ten bits, one byte”

Pick the letter A (65) and look at the waveform: find the start bit and read the data bits from left to right. Then flip one data bit with parity off, then with even parity on. Which setting notices the damage?

The UART diagram draws one frame as a square wave. For the letter A (65 = 0x41) with even parity the line reads, in time order: start 0, data 1 0 0 0 0 0 1 0, parity 0, stop 1. Choosing a byte updates the bits; choosing a data bit to flip inverts it and the readout reports the wrongly decoded byte and whether the parity check fails (it fails for any single flip when parity is on; with no parity the error is not noticed).

Figure 5.3 from “SPI: swapping bytes at full speed”

Set the controller to 0x9F and the peripheral to 0x3C. Clock once at a time and watch both registers. After how many clocks have the two bytes completely swapped places?

The SPI diagram shows two 8-bit registers. Starting with the controller holding 0x9F (10011111) and the peripheral holding 0x3C (00111100), each press of Clock once shifts both registers left by one: the controller's top bit goes into the peripheral's bottom bit over MOSI and the peripheral's top bit goes into the controller's bottom bit over MISO. After 8 clocks the controller holds 0x3C and the peripheral holds 0x9F: the bytes have swapped.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. What level does a UART transmit line sit at when nothing is being sent?

  • Low (0)
  • High (1)
  • It toggles at the baud rate

Check it in “UART: one wire, ten bits, one byte”

2. Your microcontroller prints readable text in one terminal but random symbols in another. What is the most likely difference?

  • The second terminal uses a different baud rate
  • The second terminal has a faster computer
  • The cable is too short

Check it in “UART: one wire, ten bits, one byte”

3. Why does a controller send 0x00 on MOSI while reading a byte from an SPI sensor?

  • To reset the sensor
  • Because clocking 8 bits in always clocks 8 bits out
  • To tell the sensor its address

Check it in “SPI: swapping bytes at full speed”

4. Which bus suits a colour display that needs about 1 MB/s, on a board with pins to spare?

  • UART at 115200 baud
  • I²C at 400 kHz
  • SPI at 10 MHz

Check it in “SPI: swapping bytes at full speed”

5. Which is good practice inside an interrupt handler?

  • Print a long debug message over a slow serial port
  • Set a flag or copy a value into a buffer, then return
  • Wait for another sensor to be ready
  • Run the whole control algorithm, however long it takes

Check it in “Polling or interrupts? Latency, energy and shared data”

6. A poll check takes 5 µs and runs every 1 ms. What percentage of CPU time does polling use?

Answer: %

Check it in “Polling or interrupts? Latency, energy and shared data”

7. Which tool decides the actual memory addresses where code and data end up?

  • The compiler
  • The linker, using a linker script
  • The debugger
  • The flash programmer

Check it in “From source code to running hardware, and testing the join”

8. What can a hardware-in-the-loop test catch that a unit test on a laptop cannot?

  • Spelling errors in comments
  • A wrongly configured clock that makes the control loop run at the wrong rate
  • A sorting bug in pure code
  • Nothing

Check it in “From source code to running hardware, and testing the join”

Engineering applications

Debug consoles

Almost every embedded board prints its boot log over a UART. When the text arrives as garbage, a mismatched baud rate on one end is the first suspect.

Displays and storage

Colour displays and memory cards use SPI because it clocks data both ways at many megahertz with no addressing overhead, at the cost of one chip-select pin per device.

Summary

Glossary

Interrupts
An interrupt is a hardware signal that makes the processor pause the main program, run a short interrupt service routine (ISR), and then resume where it left off.
Bus and link bandwidth
Bandwidth is how much data a bus or link can move per second. For a UART each byte usually costs 10 bit times: one start bit, eight data bits and one stop bit.
Memory-mapped I/O
With memory-mapped I/O, peripheral control and data registers appear at fixed memory addresses, so the processor talks to hardware with ordinary load and store instructions.
Endianness
Endianness is the order in which the bytes of a multi-byte value are stored in memory or sent over a link: little-endian puts the least significant byte first, big-endian the most significant.

Project: A bus and interrupt plan

For a small robot with an IMU, a range sensor, a display and a debug console, choose a bus for each device, compute the data rate each needs, and decide which raise interrupts. Show that the total bus load leaves headroom.

Deliverables

  • A device table with bus, data rate and interrupt choice
  • Bus load calculations
  • One risk at the hardware–software boundary and its mitigation

References

6. Parallelism and acceleration

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

When a single core cannot go faster, engineers add more cores or move a task into dedicated hardware. Amdahl's law is the reality check: the part you do not speed up limits the whole. This chapter applies it to loops and accelerators, weighs one fast core against several slow ones with the power, performance and area triangle, and counts the multiply–accumulate operations that make machine-learning inference a natural target for hardware.

Figure 6.1. The serial part sets the ceiling (described in words)

Amdahl's law curves for 50 %, 80 % and 95 % of the run time accelerated. At 32 times acceleration the overall speed-up is only 1.94, 4.44 and 12.55, approaching limits of 2, 5 and 20 however fast the accelerated part becomes.

Explanation

6.1 Project: then speed it up

One new instruction or one new gate path could make your multiply several times faster. Which change gives the most speed for the least hardware?

Three kinds of speed-up

Fewer instructions: a new instruction does the work of several (a combined 'decrement and jump if not zero', or a SHIFT for shift-and-add multiply). Fewer cycles per instruction: overlap fetch with execute. Shorter cycle: a faster adder (lookahead) shortens the critical path. The iron law, T = IC × CPI × T_clk, tells you which term each idea attacks.

Quantify it

Speed-up = old time ÷ new time, from your measured baseline. Changes that only touch the loop body help most when y is large; setup costs dominate when y is small. Always state the input you assumed. If a change also lengthens the clock period, include that: a 2× reduction in cycles with a 1.5× longer period is only a 1.33× speed-up.

Price it

New instructions need opcodes (Nibble has spare ones), control-table rows and possibly datapath blocks: a shifter, an extra register, a second adder. Carry lookahead uses more gates to shorten the path. A good design note gives the speed-up, the extra hardware and one risk, and recommends honestly, including 'not worth it'.

Common mix-ups

6.2 Hardware or software? Partitioning a task

Moving one function into custom hardware makes it 50 times faster. Why might the whole program only get twice as fast?

What co-design means

Co-design decides together which functions run as software on a processor and which become dedicated hardware (an accelerator, a peripheral, an FPGA block), and designs the interface between them. Software is flexible and cheap to change; hardware is fast and energy-efficient for a fixed job but costs area, design effort and verification.

When hardware wins

Good candidates are hot (a large share of run time), stable (the algorithm won't change), regular (lots of parallel, simple operations, like filtering, encryption or matrix multiply) and data-local (little traffic in and out). Poor candidates are rarely run, branchy or still evolving.

Count before you build

Profile first: measure where time goes. Use Amdahl's law to bound the gain. Then estimate the hardware: gates or multipliers needed, its latency in gate delays or cycles, and the data movement cost. The parity example shows the typical shape: software Θ(n) instructions, hardware Θ(log n) gate delays but Θ(n) gates.

Derivation: Amdahl's law
  1. Let the original run time be 1, and let a fraction p of it be the part you accelerate.

  2. The accelerated part becomes s times faster, so it takes p/s. The rest still takes 1 − p.

  3. New time = (1 − p) + p/s, so overall speed-up S = 1 / ((1 − p) + p/s).

  4. As s → ∞, S → 1/(1 − p). If only 50% of the time is accelerated, no accelerator can beat 2×.

  5. Example: p = 0.8, s = 50: S = 1/(0.2 + 0.016) ≈ 4.6×. Doubling s to 100 only gives 4.8×: optimise the other 20% next.

  6. Add the cost of moving data to and from the accelerator to the new time and the speed-up falls further.

Common mix-ups

6.3 Power, performance and area

Two slow cores can do the work of one fast core and use less energy. Why don't chips always do that?

Dynamic and static power

Dynamic power comes from charging and discharging capacitance when signals switch: α·C·V²·f. Static (leakage) power flows even when nothing switches, because transistors never turn fully off; it grows with temperature, with area and as transistors shrink. Total P = P_dyn + P_leak.

DVFS

Dynamic voltage and frequency scaling picks the lowest voltage that supports the needed clock at each moment. Busy: high V, high f. Light load: lower both, saving cube-like power (V²·f). Phones and laptops do this hundreds of times a second.

PPA is a three-way trade

Performance can be bought with clock (costs power), with parallel units (costs area) or with smarter architecture (costs design effort and area). Area costs money through yield (week 22) and leakage. 'Race to idle' (finish fast at high V, then sleep) sometimes beats running slowly, when leakage or the rest of the system dominates.

Derivation: Why lowering voltage saves energy, and what it costs
  1. Each switching event charges a capacitance C to voltage V, drawing energy C·V² from the supply. With activity α and clock f: P_dyn = α·C·V²·f.

  2. Energy per operation = P/f = α·C·V²: independent of f, quadratic in V.

  3. But gates switch more slowly at lower V. A common model: f_max ∝ (V − V_t)^α_p / V, with threshold V_t and α_p ≈ 1.3–2.

  4. To keep throughput while lowering f, add parallel units: N units at f/N give the same operations per second.

  5. N units at lower V: power ≈ N·α·C·V_low²·(f/N) = α·C·V_low²·f, less than α·C·V²·f. The price is N× the area, plus leakage on every unit.

  6. Leakage P_leak ≈ I_leak·V is paid all the time and grows with area; at very low V and f it dominates, so energy per operation has a minimum.

Common mix-ups

6.4 Training versus inference: counting the cost

Training a speech model took a data centre. Running it fits on a chip in a light switch. What makes the two so different?

Two phases

Training searches for weights that minimise a loss over a dataset, using many passes of forward computation, gradient computation and updates: expensive, done once on big hardware. Inference runs one forward pass with fixed weights on a new input: much cheaper, done millions of times, often on the device itself for latency, privacy or battery reasons.

Counting MACs

A multiply-accumulate does y ← y + w·x. A dense layer with a inputs and b outputs costs a·b MACs. A convolution producing an H×W×C_out output with k×k kernels over C_in channels costs H·W·C_out·k²·C_in. Add the layers. Activations (ReLU) and pooling are usually small by comparison.

Memory: weights and activations

Weights must be stored somewhere, usually flash: one value per connection. Activations (the intermediate results) must fit in RAM while a layer runs: roughly the largest input plus output of any layer. A microcontroller with 1 MB flash and 256 KB RAM sets hard limits on both.

From MACs to milliseconds

Latency ≈ MACs ÷ (MACs per cycle × clock rate), plus memory stalls. A core doing 1 MAC per cycle at 100 MHz runs a 2 million-MAC model in about 20 ms. Vector (SIMD) instructions or a small accelerator can do 4–8 MACs per cycle at 8 bits.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Project: then speed it up: example 1

Setup 2 cycles, 10 passes of 24 cycles. A change cuts a pass to 15 cycles but lengthens the clock period by 10 %. Speed-up?

Hardware or software? Partitioning a task: example 1

A rover's image pipeline spends 70% of its time in a 3×3 convolution. An accelerator makes convolution 30× faster but adds data copies costing 5% of the original time. Overall speed-up?

Power, performance and area: example 1

α = 0.15, C = 2 nF, V = 0.9 V, f = 2 GHz. Dynamic power? Energy per cycle?

Training versus inference: counting the cost: example 1

A network: 49×10 audio features flattened (490 inputs) → dense 64 → dense 12. MACs and weights?

Interactive figures, in words

Figure 6.2 from “Power, performance and area”

Start at 1 unit, 1.0 V, 3 GHz. Now set 2 units and lower the voltage until 1.5 GHz is still reachable. Compare throughput, power, area and energy per operation. Then find the lowest energy per operation you can reach at any throughput, and the leakage term that stops you going lower.

The PPA explorer reports throughput, power, area and energy per operation relative to one unit at 1 V and 3 GHz. Two units at about 0.7 V and 1.5 GHz give the same throughput for about 62% of the energy per operation but twice the area.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. As the loop count grows very large, the speed-up from shrinking the body from b to b' approaches…

  • 1
  • b/b'
  • b − b'
  • The setup cost

Check it in “Project: then speed it up”

2. A design halves cycle count but makes the clock period 1.5 times longer. Net effect?

  • 2× faster
  • 1.33× faster
  • 1.5× slower
  • No change

Check it in “Project: then speed it up”

3. Which function is the best candidate for a hardware accelerator in a drone?

  • The menu system of its phone app
  • A fixed FIR filter run on every IMU sample at 8 kHz
  • The mission planner that changes every flight
  • Error logging that runs once per crash

Check it in “Hardware or software? Partitioning a task”

4. A task is 40% accelerable. What is the best overall speed-up any accelerator can give?

  • 1.4×
  • About 1.67×
  • 2.5×
  • Unlimited

Check it in “Hardware or software? Partitioning a task”

5. Voltage drops from 1.1 V to 0.8 V and frequency from 2.4 GHz to 1.2 GHz. What fraction of the original dynamic power remains? (Answer as a decimal.)

Answer:

Check it in “Power, performance and area”

6. Replacing one fast core with four slow low-voltage cores at equal throughput mainly costs…

  • Power
  • Area (and leakage), plus software that can use four cores
  • Nothing
  • Clock frequency of the cores is higher

Check it in “Power, performance and area”

7. Which phase normally runs on a battery-powered sensor?

  • Training
  • Inference
  • Both, equally
  • Neither

Check it in “Training versus inference: counting the cost”

8. A model needs 3,000,000 MACs. The core does 2 MACs per cycle at 80 MHz. Ignoring memory stalls, what is the latency in ms?

Answer: ms

Check it in “Training versus inference: counting the cost”

Engineering applications

Multicore phones

Phones pair fast cores with small efficient ones. Light work runs on the small cores at low voltage; only bursts wake the big ones, because power grows faster than performance.

Accelerators in sensors

A camera chip may include a small neural-network engine. It earns its area only because inference is almost all multiply–accumulate operations, a large and regular fraction of the work.

Summary

Glossary

Amdahl's law
Amdahl's law says the overall speed-up from improving part of a task is limited by the fraction of time that part takes.
Electrical power
The power transferred in a component is the voltage across it multiplied by the current through it. For a resistor this can also be written I²R or V²/R.
ALU (arithmetic logic unit)
The ALU is the part of a processor that performs arithmetic (add, subtract) and logic (AND, OR, XOR, shifts) on values from registers, and sets status flags such as zero and carry.

Project: Is an accelerator worth it?

Choose one task in a robot or sensor (filtering, vision, inference). Estimate its share of run time with stated assumptions, the speed-up a dedicated unit could give and the overhead of moving data to it. Use Amdahl's law to recommend yes or no.

Deliverables

  • The workload breakdown with assumptions
  • Amdahl calculation including overhead
  • A recommendation with what would change it

References

7. Energy and reduced precision

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

For a battery-powered device, the number that matters is energy per useful operation, not speed. This chapter computes energy per operation and battery life, compares racing to finish then sleeping with running slowly, and shows the biggest lever of all: using fewer bits. Fixed-point formats and 8-bit quantised models shrink memory, data movement and energy, provided the accuracy requirement was written down first and checked honestly afterwards.

Figure 7.1. Fixed point: a step and a range (described in words)

A signed fixed-point number with 4 integer bits and 4 fraction bits. The step is 0.0625 and the range is −8 to 7.9375. The value 2.7 is stored as code 43, bit pattern 00101011, which means 2.6875: a rounding error of 0.0125, within half a step.

Explanation

7.1 Energy per operation: the number that decides battery life

Chip A is twice as fast as chip B but draws three times the power. Which one empties a rover's battery first doing the same job?

The unit that matters

Energy per operation = power ÷ operations per second. A 0.3 W microcontroller doing 100 million operations a second spends 3 nJ per operation; a 12 W accelerator doing 2 trillion spends 6 pJ. For the same job, the accelerator uses 500 times less energy, even though it draws 40 times more power.

System energy, not chip energy

While the processor works, other parts stay awake: memory, sensors, voltage regulators, the radio. If they draw 2 W regardless, a slow chip keeps them awake longer. Total job energy = (P_chip + P_rest) × time + sleep energy. This is why 'race to idle' (finish fast, then put everything to sleep) often wins in real systems.

Memory moves cost more than maths

On modern chips, fetching a number from off-chip memory can cost hundreds of times the energy of adding it. Energy-efficient designs keep data close: small local memories, data reuse, fewer transfers. This is a hardware–software co-design question: the algorithm's data movement decides the energy.

Duty cycling

Many sensors spend 99% of their life asleep. Average power = d·P_active + (1 − d)·P_sleep. At low duty cycles the sleep current dominates: a 10 mW sleep draw can matter more than a 2 W active draw at 0.1% duty. Battery life = energy capacity ÷ average power.

Common mix-ups

7.2 Energy budgets and duty cycling

A soil sensor must run for two years on two AA batteries. It can only be awake about one second in every hundred. How do you design for that?

Energy, not power

Batteries store energy (joules, or watt-hours). A task's cost is power × time, so a fast, power-hungry processor that finishes quickly and sleeps can use less energy than a slow, frugal one. Always compare energy per task.

Know your states

Real nodes have more than two states: deep sleep, wake-up (oscillator start, can be costly), sensing, computing, and radio transmit (often the most expensive per second). Measure or look up each, build a timeline, and add up the energy. The biggest slice is where design effort should go.

Computing less, or locally

Sending raw data by radio can cost far more energy than processing it locally and sending a short result. This is a key argument for embedded ML: a tiny on-device classifier that transmits only 'event detected' can extend battery life enormously, provided its own energy and false alarms are counted.

Derivation: Average power and battery life
  1. Over one period T, the node is active for t_on and asleep for T − t_on. Duty cycle D = t_on / T.

  2. Energy per period E = P_on·t_on + P_sleep·(T − t_on). Average power P_avg = E / T = D·P_on + (1 − D)·P_sleep.

  3. Battery energy ≈ capacity (Ah) × voltage (V) × 3600 J. Lifetime ≈ E_battery / P_avg (ignoring self-discharge and temperature).

  4. As T grows, D → 0 and P_avg → P_sleep: sleep power sets the ceiling on lifetime.

  5. Example: P_on = 15 mW, t_on = 20 ms, T = 10 s, P_sleep = 3 µW: D = 0.002, P_avg = 30 + 3 ≈ 33 µW. Two AA cells (about 2.5 Ah at 3 V ≈ 27 kJ) last about 26 years by this ideal sum; self-discharge will end them much sooner.

Common mix-ups

7.3 Reduced precision: range, resolution and error

Your filter works perfectly in Python floats. On the 16-bit chip, it slowly drifts and then explodes. What went wrong?

Qm.n formats

A signed Qm.n number has m integer bits (including sign) and n fraction bits: value = integer / 2ⁿ. Range ≈ [−2^(m−1), 2^(m−1)), step 2^(−n). Q1.15 in 16 bits covers [−1, 1) in steps of about 3×10⁻⁵. Choose m from the largest value the signal (and every intermediate result) can reach, then give the rest to n.

Where precision is lost

Rounding each result loses up to half a step. Multiplication doubles the fraction bits (Q1.15 × Q1.15 = Q2.30), so results are shifted back and rounded. Accumulation of many products needs extra headroom bits. Feedback (recursive filters, integrators) can accumulate rounding errors or sustain small oscillations (limit cycles).

Precision is a measured requirement

State the requirement first (for example, 'error under 0.5% of full scale'), then implement at candidate precisions on identical inputs, measure the error and pick the smallest that meets it with margin. The same applies to sample rate: lower rates save energy until aliasing or lag breaks the requirement. This is the method of the term project.

Common mix-ups

7.4 Quantisation: fewer bits, smaller models

Store every weight in 8 bits instead of 32 and the model is four times smaller. How much accuracy do you lose? Sometimes almost none.

Scale and zero point

A quantised tensor stores small integers plus one scale (and sometimes a zero point for asymmetric ranges, useful for ReLU outputs that are never negative). Per-channel scales, one per output channel, often keep accuracy much better than one scale for the whole layer.

Why accuracy often survives

A trained network is robust to small perturbations of its weights; int8 errors are tiny compared with the spread of the weights. Below about 4 bits, errors become comparable to the weights themselves and decisions start to flip. Outliers matter too: one huge weight stretches the scale and wastes resolution on everyone else.

Measure on held-out data

Compare float and quantised accuracy on the same held-out test set, report both with their uncertainty, and look at which inputs changed class. Calibration (choosing scales from representative data) and quantisation-aware training can recover accuracy at low bit widths. The explorer's toy classifier shows the trend only.

Derivation: Symmetric uniform quantisation and its error
  1. Choose a scale s = max|w| / (2^(b−1) − 1), so the largest weight maps to the largest integer.

  2. Quantise: q = round(w / s), clamped to the b-bit range. Dequantise: ŵ = q·s.

  3. The rounding error e = ŵ − w lies in [−s/2, s/2]. If it is roughly uniform, its RMS is s/√12.

  4. Each extra bit halves s, so it halves the error: about 6 dB better signal-to-quantisation-noise per bit.

  5. Integer MACs: Σ wᵢxᵢ ≈ s_w s_x Σ q_w q_x. The sum runs in integers (with a 32-bit accumulator) and one rescale happens at the end.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Energy per operation: the number that decides battery life: example 1

A sensor node: 20 Wh battery, active 2% of the time at 1.2 W, asleep otherwise at 5 mW. Battery life?

Energy budgets and duty cycling: example 1

A node wakes every 30 s for 50 ms at 24 mW and sleeps at 4 µW. Average power and life on a 1,000 mAh, 3.6 V cell?

Reduced precision: range, resolution and error: example 1

A gyro reads ±250 °/s and you need 0.01 °/s resolution. Pick a 16-bit signed format.

Quantisation: fewer bits, smaller models: example 1

Quantise w = 0.31 with max|w| = 0.8 to int8.

Interactive figures, in words

Figure 7.2 from “Quantisation: fewer bits, smaller models”

Sweep the bits from 16 down to 2 and read the accuracy curve. Find the smallest bit width that stays within 1 percentage point of float. Then set 1,000,000 parameters and find the smallest width that fits the 256 KB budget. Do the two answers agree?

The explorer plots accuracy of a toy classifier against bit width: 90.25% in float and at 8, 12 and 16 bits, 90% at 6 bits, about 89% at 3 and 4 bits, and about 74% at 2 bits. Footprint = parameters × bits ÷ 8; one million int8 weights take about 977 KB, so they do not fit a 256 KB budget.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. While the processor works, the rover's radio and sensors must stay on, drawing 4 W. Chip A: 2 W for 1 s. Chip B: 0.5 W for 3 s. Which uses less total energy?

  • B (lower power)
  • A: (2 + 4) × 1 = 6 J against B's (0.5 + 4) × 3 = 13.5 J
  • They are equal
  • Only the chip's energy matters

Check it in “Energy per operation: the number that decides battery life”

2. An accelerator delivers 4 × 10¹² operations per second at 8 W. What is its energy per operation, in pJ?

Answer: pJ

Check it in “Energy per operation: the number that decides battery life”

3. A device averages 50 µW from a battery storing 10,000 J. Ignoring self-discharge, how many days will it last?

Answer: days

Check it in “Energy budgets and duty cycling”

4. A node's average is 200 µW active + 3 µW sleep. Which change helps most?

  • Halve the sleep current
  • Halve the awake time per cycle
  • Use a bigger enclosure
  • Double the clock but keep awake time the same

Check it in “Energy budgets and duty cycling”

5. What is the step size (resolution) of a signed Q4.12 number?

Answer:

Check it in “Reduced precision: range, resolution and error”

6. Multiplying two Q1.15 numbers gives a 32-bit result in which format?

  • Q1.15
  • Q2.30
  • Q1.31
  • Q16.16

Check it in “Reduced precision: range, resolution and error”

7. With scale 0.02, what integer does w = −0.537 quantise to (round to nearest)?

Answer:

Check it in “Quantisation: fewer bits, smaller models”

8. Which evaluation of an int8 model is fair?

  • Accuracy on the training set
  • Accuracy of float and int8 models on the same held-out test set, with uncertainty
  • Accuracy on whichever test examples int8 gets right
  • Model size only

Check it in “Quantisation: fewer bits, smaller models”

Engineering applications

Wearables

A fitness band spends almost all its life asleep. Its battery life is set by the sleep current and how often, and for how long, it wakes, far more than by its processor's top speed.

On-device models

Storing a model's weights as 8-bit integers instead of 32-bit floats cuts its memory by four and its data movement with it; the accuracy loss must be measured on held-out data.

Summary

Glossary

Battery capacity and runtime
A battery's capacity in ampere-hours says how long it can supply a current; multiplied by its voltage it gives stored energy in watt-hours.
Electrical power
The power transferred in a component is the voltage across it multiplied by the current through it. For a resistor this can also be written I²R or V²/R.
Bits and bytes
A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values.
Two's complement (signed integers)
Two's complement represents negative integers so that ordinary binary addition still works: the top bit has a negative place value, so an n-bit number ranges from −2^(n−1) to 2^(n−1) − 1.

Project: A year on a coin cell?

Design the duty cycle of a sensor node that must report every minute for a year on a coin cell. Choose the active time, sleep current and data precision, compute the average power and battery life, and state the margin.

Deliverables

  • The energy budget per state
  • Battery-life calculation with margin
  • The chosen data format and its worst-case error

References

8. Measuring performance honestly

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Architecture claims live or die on measurements, and measurements of computers are easy to get wrong. Caches warm up, clocks throttle, background tasks interfere and one lucky run looks like a breakthrough. This chapter designs benchmarks you can trust: warm-up, interleaving and repeats, a speed-up reported as a ratio with an interval, baselines and ablations, and a comparison designed around a question rather than a favourite result.

Figure 8.1. A speed-up with its uncertainty (described in words)

A speed-up of 1.2, from 120 ms to 100 ms, drawn on a number line with an approximate 95 % interval from 1.115 to 1.285. Relative standard errors of 2 % and 3 % combine to about 3.6 % of the ratio. The whole interval lies above 1, so the improvement is supported.

Explanation

8.1 Designing a benchmark you can trust

The new version is 1.6× faster. Or the first runs were cold, the laptop was heating up and the test file was smaller. Which?

Decide before you measure

Write down the metric (median wall time per run? energy per job?), the workload (input files, sizes), the baseline (current release, built the same way), the environment (machine, power mode, other processes), the number of repeats and the decision rule ('ship if the 95% interval on speed-up is above 1.1'). Deciding afterwards invites choosing whatever looks best.

Warm-up and steady state

First runs pay for empty caches, page faults, JIT compilation and frequency ramp-up. Unless cold-start performance is what you care about (an app's launch time), discard a few warm-up runs and report steady-state. If it is what you care about, measure it deliberately with a fresh process each time.

Repeats and variance

Timing noise comes from interrupts, scheduling, thermal throttling and memory layout. Repeat enough to make the standard error small compared with the effect you care about, and report spread, not just the mean. Medians and percentiles are robust to occasional slow runs; say which you use.

Fair comparison

Same input, same build flags, same machine, same conditions. Interleave versions (A, B, A, B…) or randomise their order so slow drift affects both equally. Pin CPU frequency if you can, close other programs, and note what you couldn't control. A fair benchmark is one where the only systematic difference is the change under test.

Common mix-ups

8.2 A speed-up is a ratio: give it an interval

1.29× faster. Plus or minus what? And is 1.0 inside the interval?

From two means to one ratio

Speed-up S = t_A/t_B. With independent standard errors SE_A and SE_B: δS/S = √((SE_A/t_A)² + (SE_B/t_B)²). A 95% interval is S ± 1.96·δS. If the interval lies wholly above 1, B is faster at that confidence; if it includes 1, the data don't show a speed-up.

Compare against what matters

Statistical clarity is not the same as practical value. An interval of 1.02–1.04 is confidently above 1 but may not justify a risky change. Compare the interval with the threshold you set in your decision rule (say 1.10), not just with 1.

Ratios of noisy numbers misbehave

The quotient rule is first order. If B's relative uncertainty exceeds about 10%, the distribution of t_A/t_B is skewed and the symmetric interval misleads; use more repeats, or resample (bootstrap) the runs. Also beware averaging per-run speed-ups: the mean of ratios is not the ratio of means.

Report completely

A good line in a results table: 'Speed-up (median time, B vs A) 1.29 [1.24, 1.35], 95% CI by quotient propagation; n = 30 runs each after 3 warm-up, interleaved; same 4 MB input; laptop on mains, fixed performance mode.' Anyone can judge it, and anyone can try to reproduce it.

Common mix-ups

8.3 Benchmarking computer systems fairly

Your new code is '30% faster' on your laptop. Run it again and it's 5% slower. Which number goes in the report?

Protocol first

Fix the workload (inputs, sizes, a standard suite if one exists), the system (hardware, OS, compiler and flags, versions), conditions (power mode, temperature, background load) and the procedure: warm-up runs discarded, N timed repeats, randomised or interleaved order between the systems being compared. Write it down before running, as in Term 2's pre-registration.

Metrics

Primary metric: the one your claim rests on, chosen in advance (for example p99 latency). Secondary: throughput, energy per task, peak memory, accuracy. For distributions, report median and tail percentiles, not just the mean. Use execution time, not MIPS or GHz, as the Iron Law warns.

Uncertainty and comparison

Repeat runs vary. Report the spread (standard deviation or interquartile range) and a confidence interval for the difference between systems, from paired or interleaved runs. A 3% gain with a ±5% interval is not a demonstrated gain.

Trade-offs

Many systems win on one metric and lose on another: faster but hungrier, smaller but less accurate. A design is Pareto-optimal if nothing beats it on every metric at once. Show the front and say which point your requirement selects.

Common mix-ups

8.4 Designing an architecture comparison

Ripple-carry or carry-lookahead: which adder is 'better'? The honest answer starts with 'better at what, and how will we know?'

A measurable question

Replace 'which is better?' with something like: 'How does worst-case delay and gate count grow with width n for ripple-carry and carry-lookahead adders, for n = 4 to 32?' The question names the systems, the metrics, the conditions and the range.

Theory first

Write what you expect, with reasons: ripple delay ≈ 2n gate delays (Θ(n)); lookahead ≈ c·log₂ n (Θ(log n)) with more gates. A prediction made before measuring turns the experiment into a test. If the data disagree, that is a finding to explain, not a failure.

Fair comparison

Same gate library and delay model, same widths, same test inputs (including worst-case carry chains), equal effort on each design. Measure a range of sizes so the growth rate is visible; a single size can hide a crossover where the 'worse' design wins for small n.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Designing a benchmark you can trust: example 1

Blocked order: A runs first for 13 runs, then B for 13. The machine slows by 0.12 ms per run. Estimate the bias in B's mean.

A speed-up is a ratio: give it an interval: example 1

A = 60.0 ± 1.2 ms, B = 50.0 ± 1.5 ms. Speed-up, uncertainty and 95% interval. Does it clear a 1.10 threshold?

Benchmarking computer systems fairly: example 1

Ten paired runs of old vs new code give time differences (old − new) with mean 1.2 ms and standard deviation 2.0 ms. Is the new code faster?

Designing an architecture comparison: example 1

Write a decision rule for the term project before measuring.

Interactive figures, in words

Figure 8.2 from “Designing a benchmark you can trust”

Fix the problems one at a time and watch the speed-up and its interval after each: same input, then interleaved order, then 3 warm-up runs, then 30 repeats. Which fix moved the estimate most? Which narrowed the interval most? Re-run with new seeds to see the interval jitter.

The checker simulates per-run times for a baseline A (true 40 ms) and version B (true 31 ms on the same input, 24 ms on a smaller one), with cold-start penalties on the first three runs of each version, a slow upward drift over the session, and random noise. It plots runs in order and reports each mean with a 95% interval, the speed-up with its interval, and a checklist: warm-up of at least 3 runs, at least 10 repeats, interleaved order and the same input. Fixing all four gives speed-ups close to the true 1.29.

Figure 8.3 from “A speed-up is a ratio: give it an interval”

Choose A ÷ B. Set A = 40 with δA = 0.4 (1%) and B = 16 with δB = 0.3 (about 1.9%): the same relative uncertainties as the benchmark below, so the ratio's relative uncertainty is the same too. Read it off, then increase δB and watch it grow. Finally open the benchmark checker and compare its interval with your hand calculation.

The uncertainty calculator in quotient mode shows A ÷ B with its propagated uncertainty and a Monte Carlo histogram. For A = 40 ± 0.4 and B = 16 ± 0.3 the ratio is 2.5 with a relative uncertainty of about 2.2%, the same relative uncertainty as a 40 ± 0.4 ms against 31 ± 0.6 ms benchmark, and the simulation agrees with the formula. Raising δB widens the histogram and eventually skews it, which is when the symmetric formula becomes unreliable.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Why discard the first few runs of a steady-state benchmark?

  • They are always outliers caused by bugs
  • They include one-off costs (cold caches, page faults, JIT) that don't represent steady-state performance
  • To make the results look better
  • Because the timer isn't ready

Check it in “Designing a benchmark you can trust”

2. Why interleave runs of A and B rather than running all A then all B?

  • It's faster
  • Slow drift (heat, background tasks) then affects both versions equally instead of biasing one
  • It reduces noise to zero
  • It doesn't matter

Check it in “Designing a benchmark you can trust”

3. Which decision rule is best written before running the benchmark?

  • We'll decide once we see the numbers
  • Ship if the 95% interval on the median-time speed-up lies entirely above 1.10
  • Ship if it looks faster
  • Ship if any run of B beats the best run of A

Check it in “Designing a benchmark you can trust”

4. A speed-up is reported as 1.08 with 95% interval 0.97–1.19. What should the report conclude?

  • B is 8% faster
  • The data don't show B is faster: the interval includes 1
  • B is slower
  • The benchmark is invalid

Check it in “A speed-up is a ratio: give it an interval”

5. Why not compute the speed-up as the average of per-run ratios t_A,i / t_B,i?

  • It's the same as the ratio of means
  • The mean of ratios is biased and depends on arbitrary pairing; the ratio of means (or medians) is the standard
  • Ratios can't be averaged
  • It's always more accurate

Check it in “A speed-up is a ratio: give it an interval”

6. Design A: 10 ms, 50 mJ. B: 12 ms, 30 mJ. C: 14 ms, 55 mJ. Which are Pareto-optimal (lower is better on both)?

  • A only
  • A and B
  • B and C
  • All three

Check it in “Benchmarking computer systems fairly”

7. Which practice makes a two-system timing comparison fairest?

  • Run all of A, then all of B, on a warming laptop
  • Interleave A and B runs on a fixed-frequency machine, same inputs, with the order randomised
  • Run each once on different machines
  • Use whichever run of each was fastest

Check it in “Benchmarking computer systems fairly”

8. Why measure several sizes rather than one?

  • It looks better in a report
  • Growth rates and crossovers only show up across sizes; one point can mislead
  • It is required by law
  • Smaller sizes are always more accurate

Check it in “Designing an architecture comparison”

Engineering applications

Summarising a suite

When speed-ups across several programs are combined, the geometric mean is used for ratios. An arithmetic mean of ratios can rank two machines differently depending on which one is the reference.

Shipping an optimisation

A team adopts a compiler change only if the interval on its speed-up excludes 1 across the workloads they care about, measured on the target hardware rather than a laptop.

Summary

Glossary

Repeated trials
Repeating a measurement or test several times shows how much results vary and lets you average out random error.
Standard error of the mean
The standard error of the mean estimates how much a sample mean would vary between repeated experiments: the sample standard deviation divided by the square root of the number of readings.
Baselines and control conditions
A baseline is the reference condition a new idea is compared with, such as the existing design or a simple method, tested in the same way.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.

Project: An architecture comparison you would defend

Compare two designs in a School simulation (two adders, two cache settings or two pipeline options). Write the question and decision rule first, measure several sizes with repeats, and report speed-ups with intervals. Explain the result from first principles.

Deliverables

  • The question and decision rule, dated before the runs
  • A results table with intervals at each size
  • A first-principles explanation and the limitations

References

Known limitations