SyntaxPilot
Courses/CS Fundamentals for Placements/Lesson 6

CS Fundamentals for Placements · Lesson 6 of 90 · 14 min

Inside the CPU: registers, ALU, control unit and the instruction cycle

ALUcontrol unitregister filegeneral-purpose registersprogram counter (PC)instruction register (IR)MARMDRaccumulatorstatus/flag register (zero, carry, sign, overflow)stack pointersystem busaddress busdata bus

These are the notes for CS Fundamentals for Placements, episode 6. Last episode we built an adder and memory cells out of logic gates. But an adder doesn't know what to add, or when. Here you put the parts together into a working CPU, one problem at a time: the ALU and the control unit, registers (the accumulator, general-purpose registers, the register file), the program counter and instruction register, the fetch-decode-execute cycle, the system bus (address, data and control buses) with addressable-memory numericals, MAR, MDR and register-transfer notation, the flag register, interrupts, ISRs and the stack pointer, hardwired vs microprogrammed control, and CPU performance: clock rate, CPI, the CPU time equation, MIPS and Amdahl's law. Every term is explained in plain words, and there is a full glossary at the end. All outputs below are real: every program was run with Python 3.13. The CPUs in the numericals are made up.

A quick refresher: a bit is one 0 or 1, a byte is 8 bits, the MSB (most significant bit) is the leftmost bit. The CPU (central processing unit) is the chip that runs programs. Memory (main memory, RAM) is a long row of numbered boxes; a box's number is its address.

The seven problems

Problem What it teaches
Who decides what to add? ALU, control unit, registers
Which step are we on? Program counter, instruction register, fetch-decode-execute
How does the CPU talk to RAM? System bus, bus width, addressable memory, MAR, MDR, micro-operations
Loops and ifs Flags (zero, carry, sign, overflow) and jumps
A key is pressed mid-program Polling vs interrupts, interrupt cycle, ISR, stack pointer
How is the boss built? Hardwired vs microprogrammed control
Which CPU is faster? Clock rate, CPI, CPU time, MIPS, speedup, Amdahl's law

Problem 1: who decides? (ALU, control unit, registers)

Think of a restaurant kitchen.

A kitchen A CPU
The cook's hands: chop, fry, mix. They do the work ALU (Arithmetic Logic Unit): adds, subtracts, does AND, OR, NOT, compares. It contains last episode's adder
The head chef: reads each order, says what's next. He doesn't cook Control unit (CU): reads each instruction and sends control signals
The cook's counter: things in use, within reach Registers: a few tiny, very fast storage boxes inside the CPU

A control signal is one wire the control unit switches on to make one part act: "ALU, add now", "memory, read now", "copy this register into that one".

Why not keep every value in RAM? Reaching main memory takes many clock ticks; reaching a register takes about one. The cook doesn't walk to the storeroom for every pinch of salt. So working values live in registers, built from the flip-flops (one-bit memory circuits) of last episode. Registers are the fastest and smallest storage in a computer.

Register Job Example
Accumulator (ACC) In a simple CPU, the one register holding the running result ADD 8: ACC = ACC + mem[8]
General-purpose registers (GPRs) Many registers (R0, R1 ...) that can hold any data R1 = R2 + R3
Register file The whole set of GPRs, each with a number: a tiny numbered memory inside the CPU 16 registers, 0 to 15
Program counter (PC) Address of the next instruction PC = 2 while address 1 runs
Instruction register (IR) The instruction being run now IR = ADD 8
MAR, MDR Address and data at the door to memory Problem 3
Flag register Bits describing the last result Problem 4
Stack pointer (SP) Address of the top of the stack Problem 5

Problem 2: which step are we on? (PC, IR, fetch-decode-execute)

address 0:  LOAD 7    ACC = mem[7]
address 1:  ADD 8     ACC = ACC + mem[8]
address 2:  STORE 9   mem[9] = ACC
address 3:  HALT      stop
address 7:  25        address 8:  17        address 9:  0
  • An instruction is one command the CPU understands. It has an opcode (operation code: what to do: LOAD, ADD, STORE, HALT) and an operand (on what: here a memory address like 7).
  • LOAD x copies mem[x] into ACC, ADD x adds mem[x] to ACC, STORE x copies ACC into mem[x], HALT stops.
  • Program (addresses 0-3) and data (7-9) share the same memory: the stored-program idea, or von Neumann design (episode 1). Instructions are just numbers in memory.

The failing attempt: a CPU that forgets to move on

Each cycle (one round of the loop) the CPU copies the instruction at PC into IR, splits it, and does it. But one line is commented out:

# a tiny accumulator CPU: memory holds the program AND the data
mem = ["LOAD 7", "ADD 8", "STORE 9", "HALT", 0, 0, 0, 25, 17, 0]
PC, ACC = 0, 0

for cycle in range(6):
    IR = mem[PC]                    # FETCH: copy the instruction at PC
    # PC = PC + 1                 (forgot to move on)
    op, *arg = IR.split()           # DECODE: split opcode and address
    if op == "LOAD":    ACC = mem[int(arg[0])]          # EXECUTE
    elif op == "ADD":   ACC = ACC + mem[int(arg[0])]
    elif op == "STORE": mem[int(arg[0])] = ACC
    elif op == "HALT":  break
    print(f"PC={PC}  IR={IR:8}  ACC={ACC}")

print("mem[9] =", mem[9])

Output:

PC=0  IR=LOAD 7    ACC=25
PC=0  IR=LOAD 7    ACC=25
PC=0  IR=LOAD 7    ACC=25
PC=0  IR=LOAD 7    ACC=25
PC=0  IR=LOAD 7    ACC=25
PC=0  IR=LOAD 7    ACC=25
mem[9] = 0
  • op, *arg = IR.split() turns "LOAD 7" into op = "LOAD", arg = ["7"]; {IR:8} pads to 8 characters.
  • Why it fails: nothing changes PC, so every fetch reads address 0. A real CPU would run LOAD 7 forever (we stop after 6 cycles), and mem[9] is never written.

The fix: the program counter moves on

# a tiny accumulator CPU: memory holds the program AND the data
mem = ["LOAD 7", "ADD 8", "STORE 9", "HALT", 0, 0, 0, 25, 17, 0]
PC, ACC = 0, 0

for cycle in range(6):
    IR = mem[PC]                    # FETCH: copy the instruction at PC
    PC = PC + 1                     #        and point PC at the next one
    op, *arg = IR.split()           # DECODE: split opcode and address
    if op == "LOAD":    ACC = mem[int(arg[0])]          # EXECUTE
    elif op == "ADD":   ACC = ACC + mem[int(arg[0])]
    elif op == "STORE": mem[int(arg[0])] = ACC
    elif op == "HALT":  break
    print(f"PC={PC}  IR={IR:8}  ACC={ACC}")

print("mem[9] =", mem[9])

Output:

PC=1  IR=LOAD 7    ACC=25
PC=2  IR=ADD 8     ACC=42
PC=3  IR=STORE 9   ACC=42
mem[9] = 42
  • LOAD gives 25, ADD gives 25 + 17 = 42, STORE writes it, HALT stops (the break comes before the print, so HALT has no line).
  • Line 1: while LOAD 7 is in IR, PC already says 1. PC holds the address of the next instruction; IR holds the current one.

This loop is the fetch-decode-execute cycle, also called the instruction cycle, and every CPU runs it billions of times a second:

FETCH:    IR <- mem[PC],  PC <- PC + 1
DECODE:   the control unit works out opcode and operand
EXECUTE:  the ALU computes, memory is read or written, or PC is changed (a jump)
repeat until HALT

Problem 3: talking to memory (buses, MAR, MDR)

A shop and its warehouse CPU and RAM
The shelf number you call out (shop → warehouse) Address bus: carries the address, CPU → memory, one direction
The box that comes back, or goes in Data bus: carries the data, both directions
The slip: "send" or "take this" Control bus: read, write, clock and interrupt signals

A bus is a shared set of wires. All three together form the system bus.

+------------------------------ CPU ------------------------------+
|  Control unit --control signals--> ALU, registers               |
|  ALU <-> ACC / register file     PC    IR    flags    SP        |
|          MAR (address)                MDR (data)                |
+------------|---------------------------|------------------------+
     address bus (CPU -> memory)    data bus (both ways)    control bus (read, write, clock, interrupt)
             |                           |                          |
+------------v---------------------------v--------------------------v--+
|  MEMORY (RAM):  0: LOAD 7   1: ADD 8   2: STORE 9  ...  7: 25         |
+-----------------------------------------------------------------------+
            I/O devices (keyboard, disk) hang on the same bus

Bus width and addressable memory

The bus width is its number of wires. Each address wire is one bit of the address, so n address lines name 2ⁿ addresses. How much memory that is depends on what one address holds:

  • Byte-addressable: each address names one byte → capacity 2ⁿ bytes.
  • Word-addressable: each address names one word (a fixed group of bytes the CPU handles at once, e.g. 4) → capacity 2ⁿ words.
  • KiB (kibibyte) = 2¹⁰ = 1,024 bytes, MiB = 2²⁰, GiB = 2³⁰ bytes. Strictly, KB, MB, GB mean 10³, 10⁶, 10⁹.
  • Data bus width = bits moved in one trip (one bus transfer).
# addressable memory and bus numericals
import math
KiB, MiB, GiB = 2**10, 2**20, 2**30
for n in [16, 24, 28, 32]:                    # n address lines -> 2**n addresses
    print(f"{n} lines -> {2**n:>13,} addresses")

def lines_for(capacity_bytes, word_bytes=1):  # log2 of how many things need an address
    return int(math.log2(capacity_bytes // word_bytes))

print("64 KiB,  byte-addressable ->", lines_for(64 * KiB), "lines")
print("256 MiB, byte-addressable ->", lines_for(256 * MiB), "lines")
print("4 GiB,   byte-addressable ->", lines_for(4 * GiB), "lines")
print("4 GiB,   4-byte words     ->", lines_for(4 * GiB, 4), "lines")
print("8-byte value, 32-bit data bus ->", math.ceil(8 * 8 / 32), "trips")

Output:

16 lines ->        65,536 addresses
24 lines ->    16,777,216 addresses
28 lines ->   268,435,456 addresses
32 lines -> 4,294,967,296 addresses
64 KiB,  byte-addressable -> 16 lines
256 MiB, byte-addressable -> 28 lines
4 GiB,   byte-addressable -> 32 lines
4 GiB,   4-byte words     -> 30 lines
8-byte value, 32-bit data bus -> 2 trips
  • 16 lines → 65,536 = 64 KiB (byte-addressed); 24 → 16 MiB; 28 → 256 MiB; 32 → 4 GiB. A plain 32-bit address reaches at most 4 GiB.
  • Lines from capacity: lines = log₂(number of addressable things). 64 KiB = 2⁶ × 2¹⁰ = 2¹⁶ → 16.
  • Word-addressable needs fewer lines: 4 GiB of 4-byte words = 2³² / 2² = 2³⁰ words → 30, not 32.
  • An 8-byte (64-bit) value over a 32-bit data bus: 64 / 32 = 2 trips.

MAR and MDR, and the fetch micro-steps

  • MAR (Memory Address Register): holds the address to use; it drives the address bus.
  • MDR (Memory Data Register): holds data coming from or going to memory (some books say MBR, memory buffer register).

Each tiny register-to-register step is a micro-operation, written in register-transfer notation (RTN): X ← Y means "copy Y into X", M[a] is "memory at address a", and T1, T2 ... are clock ticks. Steps on one line happen in the same tick.

FETCH (same for every instruction)
T1: MAR ← PC
T2: MDR ← M[MAR],  PC ← PC + 1      (READ on the control bus)
T3: IR  ← MDR

The video puts PC ← PC + 1 in step 3; either works, since PC is free after T1. Execute depends on the opcode (IR(address) = the operand part of IR):

Instruction T4 T5 T6
LOAD X MAR ← IR(address) MDR ← M[MAR] ACC ← MDR
ADD X MAR ← IR(address) MDR ← M[MAR] ACC ← ACC + MDR (ALU adds)
STORE X MAR ← IR(address) MDR ← ACC M[MAR] ← MDR (WRITE signal)

The same program, run one micro-operation at a time:

# the same program, one micro-operation at a time (register-transfer view)
M = ["LOAD 7", "ADD 8", "STORE 9", "HALT", 0, 0, 0, 25, 17, 0]
PC, MAR, MDR, IR, ACC = 0, 0, 0, "", 0

while True:
    MAR = PC;                print(f"T1: MAR <- PC          MAR={MAR}")
    MDR = M[MAR]; PC += 1;   print(f"T2: MDR <- M[MAR], PC <- PC + 1   MDR={MDR!r} PC={PC}")
    IR = MDR;                print(f"T3: IR  <- MDR         IR={IR!r}")
    op, *arg = IR.split()
    if op == "HALT":
        print("decode: HALT, stop"); break
    MAR = int(arg[0]);       print(f"T4: MAR <- IR(address) MAR={MAR}")
    if op == "LOAD":
        MDR = M[MAR];        print(f"T5: MDR <- M[MAR]      MDR={MDR}")
        ACC = MDR;           print(f"T6: ACC <- MDR         ACC={ACC}")
    elif op == "ADD":
        MDR = M[MAR];        print(f"T5: MDR <- M[MAR]      MDR={MDR}")
        ACC = ACC + MDR;     print(f"T6: ACC <- ACC + MDR   ACC={ACC}")
    elif op == "STORE":
        MDR = ACC;           print(f"T5: MDR <- ACC         MDR={MDR}")
        M[MAR] = MDR;        print(f"T6: M[MAR] <- MDR      M[{MAR}]={M[MAR]}")
    print("---")

Output:

T1: MAR <- PC          MAR=0
T2: MDR <- M[MAR], PC <- PC + 1   MDR='LOAD 7' PC=1
T3: IR  <- MDR         IR='LOAD 7'
T4: MAR <- IR(address) MAR=7
T5: MDR <- M[MAR]      MDR=25
T6: ACC <- MDR         ACC=25
---
T1: MAR <- PC          MAR=1
T2: MDR <- M[MAR], PC <- PC + 1   MDR='ADD 8' PC=2
T3: IR  <- MDR         IR='ADD 8'
T4: MAR <- IR(address) MAR=8
T5: MDR <- M[MAR]      MDR=17
T6: ACC <- ACC + MDR   ACC=42
---
T1: MAR <- PC          MAR=2
T2: MDR <- M[MAR], PC <- PC + 1   MDR='STORE 9' PC=3
T3: IR  <- MDR         IR='STORE 9'
T4: MAR <- IR(address) MAR=9
T5: MDR <- ACC         MDR=42
T6: M[MAR] <- MDR      M[9]=42
---
T1: MAR <- PC          MAR=3
T2: MDR <- M[MAR], PC <- PC + 1   MDR='HALT' PC=4
T3: IR  <- MDR         IR='HALT'
decode: HALT, stop

{MDR!r} prints with quotes, so you can see an instruction ('LOAD 7') travel through MDR exactly like data (25). Every memory access goes through MAR and MDR; the ALU never talks to RAM directly.

Problem 4: making decisions (flags and jumps)

Our CPU only walks straight down the list. Two new instructions: SUB x (ACC = ACC - mem[x]) and JNZ a, "jump if not zero". A jump (or branch) is the CPU writing a new value into PC; a conditional jump does it only if a condition holds.

# count down from 3 with a jump and a zero flag
mem = ["LOAD 9", "SUB 10", "STORE 9", "JNZ 0", "HALT",
       0, 0, 0, 0, 3, 1]
PC, ACC, Z = 0, 0, 0

while True:
    IR = mem[PC]; PC += 1                       # fetch
    op, *arg = IR.split()                        # decode
    a = int(arg[0]) if arg else 0
    if op == "LOAD":  ACC = mem[a]               # execute
    elif op == "SUB": ACC = ACC - mem[a]
    elif op == "STORE": mem[a] = ACC
    elif op == "JNZ" and not Z: PC = a           # jump if not zero
    elif op == "HALT": break
    Z = 1 if ACC == 0 else 0                     # set the zero flag
    print(f"{IR:8} ACC={ACC}  Z={Z}  PC={PC}")

Output:

LOAD 9   ACC=3  Z=0  PC=1
SUB 10   ACC=2  Z=0  PC=2
STORE 9  ACC=2  Z=0  PC=3
JNZ 0    ACC=2  Z=0  PC=0
LOAD 9   ACC=2  Z=0  PC=1
SUB 10   ACC=1  Z=0  PC=2
STORE 9  ACC=1  Z=0  PC=3
JNZ 0    ACC=1  Z=0  PC=0
LOAD 9   ACC=1  Z=0  PC=1
SUB 10   ACC=0  Z=1  PC=2
STORE 9  ACC=0  Z=1  PC=3
JNZ 0    ACC=0  Z=1  PC=4
  • mem[9] is the counter (3), mem[10] the constant 1. JNZ sets PC back to 0, so the body runs for 3, 2, 1.
  • When ACC hits 0, Z becomes 1, JNZ doesn't jump, PC moves on to 4 (HALT). Z is a flag: one bit the ALU sets to describe its last result.

All flags live in the status register, also called the flag register (or PSW, program status word):

Flag Set to 1 when Example (8-bit)
Zero (Z) The result was 0 5 - 5 → Z = 1
Carry (C) A 1 fell off the left end (unsigned overflow, episode 3) 200 + 100 → 44, C = 1
Sign (S or N) Copy of the result's MSB: 1 means negative 3 - 5 = 11111110 (-2) → S = 1
Overflow (V) A signed result came out with the wrong sign 100 + 50 → -106, V = 1

Every if, while and for becomes a compare (a subtraction that keeps only the flags) plus a conditional jump that reads them: if (x == y) is "compare x, y; jump if Z = 1".

Problem 5: a key is pressed (interrupts)

Waiting for a parcel CPU
Walk to the door every minute; nothing else gets done Polling: the CPU keeps asking a device "anything for me?", wasting time
The doorbell rings; you bookmark your page Interrupt: a device's signal "stop and deal with me"; the CPU saves its PC
Take the parcel: a short, special job ISR (interrupt service routine, interrupt handler): a small routine that serves the device
Open the book at the bookmark Restore the saved PC and carry on

After every instruction the CPU checks the interrupt line: the interrupt cycle. The ISR lives at address 50; a key arrives during cycle 2.

mem = {0: "ADD 1", 1: "ADD 1", 2: "ADD 1", 3: "ADD 1", 4: "HALT",
       50: "READKEY", 51: "RETI"}                # the ISR lives at 50
PC, ACC, stack = 0, 0, []
key_pressed_at = 2                               # a key arrives during cycle 2

for cycle in range(10):
    IR = mem[PC]; PC += 1                        # fetch
    op, *arg = IR.split()                        # decode, execute
    if op == "ADD":       ACC += int(arg[0])
    elif op == "READKEY": print("   ISR: key 'A' saved")
    elif op == "RETI":    PC = stack.pop()       # return from interrupt
    elif op == "HALT":    break
    print(f"cycle {cycle}: {IR:8} ACC={ACC} PC={PC}")
    if cycle == key_pressed_at:                  # INTERRUPT CYCLE
        stack.append(PC)                         # save where we were
        PC = 50                                  # jump to the ISR
        print("   interrupt! saved PC =", stack[-1])

Output:

cycle 0: ADD 1    ACC=1 PC=1
cycle 1: ADD 1    ACC=2 PC=2
cycle 2: ADD 1    ACC=3 PC=3
   interrupt! saved PC = 3
   ISR: key 'A' saved
cycle 3: READKEY  ACC=3 PC=51
cycle 4: RETI     ACC=3 PC=3
cycle 5: ADD 1    ACC=4 PC=4
  • Here ADD 1 adds the number 1 (not mem[1]); memory is a dictionary so the ISR can sit at 50.
  • After cycle 2 the CPU pushes PC = 3 (the bookmark) and loads 50 into PC. "ISR: key 'A' saved" prints before the "cycle 3" line because READKEY prints while executing.
  • RETI (return from interrupt) pops 3 back into PC, and the program carries on: ACC goes 3, then 4.

Stack and stack pointer. A stack is memory used last in, first out (LIFO), like a pile of plates. Push puts a value on top; pop takes the top one off. The stack pointer (SP) register holds the address of the top. Stacks usually grow down: push is SP ← SP - 1; M[SP] ← value, pop is value ← M[SP]; SP ← SP + 1. Function calls save their return address there too (CALL pushes PC and jumps, RET pops it), and LIFO makes nested calls and nested interrupts return in the right order.

Interrupt handling, step by step

  1. Finish the current instruction. Interrupts are checked only between instructions.
  2. Save the context: push PC and the flag register (the ISR saves any other registers it uses).
  3. Disable further interrupts (clear the interrupt-enable flag) so a second one can't break the saving.
  4. Vector to the ISR: load its start address into PC.
  5. Run the ISR (read the key, clear the device's request).
  6. Restore the saved registers and flags.
  7. RETI: pop PC, re-enable interrupts; the program continues exactly where it was.

So the full instruction cycle is fetch → decode → execute → interrupt cycle (if an enabled interrupt is waiting: push PC, PC ← ISR address; else fetch the next instruction).

  • Maskable interrupt: can be ignored for a while by clearing the interrupt-enable flag (masking). Example: keyboard, timer.
  • Non-maskable interrupt (NMI): cannot be switched off; for emergencies like a power-failure warning.
  • Vectored interrupt: the device sends a number that selects its ISR from an interrupt vector table (a table in memory of ISR start addresses): device 2 → entry 2 → ISR at 0x0400. A non-vectored interrupt jumps to one fixed address, and the ISR must poll devices to find the caller.
  • Software interrupts are instructions a program runs on purpose (e.g. to ask the operating system for a service); exceptions are raised by errors inside the CPU (divide by zero). Both are handled the same way.

Problem 6: how is the control unit built?

Hardwired control Microprogrammed control
Idea A fixed gate circuit turns (opcode + step T1, T2 ...) into control signals Each instruction is a small program of microinstructions in control memory, stepped through: a CPU inside the CPU
Speed Very fast Slower: an extra memory lookup per step
Changing it / adding instructions Hard: redesign the circuit Easy: rewrite control memory
Suits RISC CPUs (few, simple instructions) CISC CPUs (many complex instructions)
  • A microinstruction is one control-memory word: which control signals to turn on this tick, and which microinstruction comes next. Control memory is the small fast memory inside the control unit that holds all microprograms.
  • Horizontal microcode: one bit per control signal (64 signals → 64 bits). Wide, many signals at once, no decoding, fast.
  • Vertical microcode: signals encoded into short fields and decoded first (64 mutually exclusive signals → log₂ 64 = 6 bits). Narrow, less memory, slower.
  • RISC (reduced instruction set computer): few, simple, fixed-size instructions, mostly one cycle. CISC (complex instruction set computer): many instructions, some doing a lot of work, like a memory-to-memory add. More next episode.

Problem 7: which CPU is faster? (performance)

  • A CPU moves in step with a clock, a signal ticking at a fixed rate; one tick is a clock cycle.
  • Clock rate = ticks per second, in hertz (Hz); 1 GHz = 10⁹ ticks per second.
  • Clock period (cycle time) = 1 / clock rate: 4 GHz → 0.25 ns (nanosecond = 10⁻⁹ s).
  • CPI (cycles per instruction) = average clock cycles one instruction takes. Instruction count (IC) = instructions the program actually runs.

CPU time = IC × CPI × clock period = IC × CPI ÷ clock rate. MIPS (millions of instructions per second) = clock rate ÷ (CPI × 10⁶). Speedup of B over A = time of A ÷ time of B.

# CPU time = instructions x CPI / clock rate
instructions = 2_000_000_000          # 2 billion instructions
clock_hz     = 4_000_000_000          # 4 GHz
for name, cpi in [("CPU A", 2.0), ("CPU B", 1.2)]:
    seconds = instructions * cpi / clock_hz
    mips = clock_hz / (cpi * 1_000_000)
    print(f"{name}: CPI={cpi}  time={seconds:.2f} s  MIPS={mips:.0f}")

# Amdahl's law: speed up 80% of the program by s times
f = 0.8
for s in [2, 4, 10, 1000]:
    print(f"part x{s:<5} -> whole program x{1 / ((1 - f) + f / s):.2f}")

Output:

CPU A: CPI=2.0  time=1.00 s  MIPS=2000
CPU B: CPI=1.2  time=0.60 s  MIPS=3333
part x2     -> whole program x1.67
part x4     -> whole program x2.50
part x10    -> whole program x3.57
part x1000  -> whole program x4.98

Same 4 GHz clock, but A takes 1.00 s and B 0.60 s: B is 1.00 / 0.60 = 1.67 times faster, purely because of CPI. GHz alone tells you nothing without CPI and instruction count. (2_000_000_000 is Python's digit-separator syntax; {s:<5} left-aligns in 5 characters.)

More numericals: clock period, CPI from a mix, faster clock vs lower CPI

CPI from an instruction mix is a weighted average: each class's CPI times its share of the instructions, summed.

Instruction class Share CPI Share × CPI
ALU 50% 1 0.50
Load 20% 3 0.60
Store 10% 2 0.20
Branch 20% 2 0.40
Total 100% 1.70
# performance numericals (made-up CPUs)
print(f"clock period at 2.5 GHz = {1 / 2.5e9 * 1e9:.2f} ns")

mix = [("ALU", 0.50, 1), ("load", 0.20, 3), ("store", 0.10, 2), ("branch", 0.20, 2)]
cpi = sum(share * cycles for _, share, cycles in mix)     # weighted average
ic, clock = 3_000_000_000, 2_000_000_000                  # 3e9 instructions, 2 GHz
print(f"CPI = {cpi:.2f}  time = {ic * cpi / clock:.2f} s  MIPS = {clock / (cpi * 1e6):.1f}")

p = 1e9 * 2.0 / 3.0e9            # P: 3 GHz, CPI 2.0, 1e9 instructions
q = 1e9 * 1.5 / 2.5e9            # Q: 2.5 GHz, CPI 1.5
print(f"P: {p:.3f} s  Q: {q:.3f} s  speedup of Q over P = {p / q:.2f}")

Output:

clock period at 2.5 GHz = 0.40 ns
CPI = 1.70  time = 2.55 s  MIPS = 1176.5
P: 0.667 s  Q: 0.600 s  speedup of Q over P = 1.11
  • CPU time = 3 × 10⁹ × 1.70 / 2 × 10⁹ = 2.55 s; MIPS = 2000 / 1.7 ≈ 1176.5.
  • Q has the slower clock but wins by 1.11×, because its CPI is lower.

Amdahl's law

You make one part faster (a better ALU, more cores). Is the whole program that much faster? If a fraction f of the original time is sped up s times, and the rest (1 - f) is untouched:

overall speedup = 1 ÷ ((1 - f) + f ÷ s)

  • f = 0.8, s = 4: 1 ÷ (0.2 + 0.2) = 2.5, not 4.
  • Limit: as s → ∞, f ÷ s → 0, so speedup can never beat 1 ÷ (1 - f): 5 for f = 0.8. The untouched 20% sets the limit.
  • Solving for s: f ÷ s = 1 ÷ target - (1 - f), so s = f ÷ (1 ÷ target - (1 - f)). If the bracket is ≤ 0, the target is impossible (or needs infinite s when exactly 0).
  • Lesson: make the common case fast.
# Amdahl's law: overall = 1 / ((1 - f) + f / s)
from fractions import Fraction as F

def overall(f, s):
    return 1 / ((1 - f) + f / s)

def needed_s(f, target):               # solve overall(f, s) = target for s
    rest = 1 / F(target) - (1 - f)     # time left for the sped-up part
    if rest > 0:  return f"s = {float(f / rest):g}"
    if rest == 0: return "only with s = infinity"
    return "impossible"

print(f"f=0.8, s=4      -> {overall(0.8, 4):.2f}")
print(f"f=0.5, s=10     -> {overall(0.5, 10):.2f}")
print(f"f=0.95, s=20    -> {overall(0.95, 20):.2f}")
for f in [0.5, 0.8, 0.9, 0.95]:
    print(f"limit for f={f:<4} -> {1 / (1 - f):.0f}")
for f, target in [(F(3, 4), 2), (F(4, 5), 4), (F(4, 5), 5), (F(4, 5), 6)]:
    print(f"f={float(f)}, want x{target}: {needed_s(f, target)}")

Output:

f=0.8, s=4      -> 2.50
f=0.5, s=10     -> 1.82
f=0.95, s=20    -> 10.26
limit for f=0.5  -> 2
limit for f=0.8  -> 5
limit for f=0.9  -> 10
limit for f=0.95 -> 20
f=0.75, want x2: s = 3
f=0.8, want x4: s = 16
f=0.8, want x5: only with s = infinity
f=0.8, want x6: impossible

Fraction keeps exact values like 4/5. With plain floats, 1/5 - (1 - 0.8) leaves a tiny rounding error, and the "x5" case would wrongly print a huge finite s. By hand: f = 0.8, want 4×: 1/4 - 0.2 = 0.05, s = 0.8 / 0.05 = 16.

Common mistakes (and the real output)

Mistake Real output Fix
Fetching without PC = PC + 1 PC=0 IR=LOAD 7 ACC=25 on every line Increment PC during fetch
"PC holds the current instruction" after fetching address 0: PC=1 IR='LOAD 7' PC = address of the next instruction; IR = current one
Comparing CPUs by GHz only same 4 GHz: time=1.00 s vs time=0.60 s time = IC × CPI ÷ clock rate
"Speed up 80% by 1000× → 1000× faster" part x1000 -> whole program x4.98 Amdahl; limit 1 ÷ (1 - f)
Plain average of CPIs plain average CPI = 2.00 weighted CPI = 1.70 Weight each CPI by its share
Trusting MIPS across instruction sets CPU X: MIPS=4000 time=2.50 s vs CPU Y: MIPS=2000 time=2.00 s Compare CPU time on the same program
2³² bytes = "4 GB" 2**32 = 4,294,967,296 vs 4 GB = 4,000,000,000 2³² bytes = 4 GiB
Counting bytes in word-addressable memory 1 GiB, 4-byte words: lines = 28 (not 30) Lines = log₂(number of words)
Interrupt without saving PC IndexError: pop from empty list Push PC (and flags) before jumping to the ISR

The program behind rows 2 and 5 to 8:

# common mistakes, measured
# 1. "PC holds the current instruction": look right after one fetch
mem = ["LOAD 7", "ADD 8", "STORE 9", "HALT"]
PC = 0
IR = mem[PC]; PC = PC + 1
print(f"after fetching address 0: PC={PC}  IR={IR!r}")

# 2. GB vs GiB
print("2**32 =", f"{2**32:,}", " vs 4 GB =", f"{4 * 10**9:,}")

# 3. plain average of CPIs instead of a weighted one
mix = [(0.50, 1), (0.20, 3), (0.10, 2), (0.20, 2)]
plain = sum(c for _, c in mix) / len(mix)
weighted = sum(share * c for share, c in mix)
print(f"plain average CPI = {plain:.2f}   weighted CPI = {weighted:.2f}")

# 4. higher MIPS but slower (different instruction counts)
for name, ic, cpi in [("X", 10_000_000_000, 1.0), ("Y", 4_000_000_000, 2.0)]:
    clock = 4_000_000_000
    print(f"CPU {name}: MIPS={clock / (cpi * 1e6):.0f}  time={ic * cpi / clock:.2f} s")

# 5. word-addressable memory counted in bytes
import math
print(f"1 GiB, 4-byte words: lines = {int(math.log2(2**30 // 4))} (not {int(math.log2(2**30))})")

Output:

after fetching address 0: PC=1  IR='LOAD 7'
2**32 = 4,294,967,296  vs 4 GB = 4,000,000,000
plain average CPI = 2.00   weighted CPI = 1.70
CPU X: MIPS=4000  time=2.50 s
CPU Y: MIPS=2000  time=2.00 s
1 GiB, 4-byte words: lines = 28 (not 30)

The last row is the interrupt demo with stack.append(PC) commented out and the print changed to print(" interrupt! (PC not saved)"). Output:

cycle 0: ADD 1    ACC=1 PC=1
cycle 1: ADD 1    ACC=2 PC=2
cycle 2: ADD 1    ACC=3 PC=3
   interrupt! (PC not saved)
   ISR: key 'A' saved
cycle 3: READKEY  ACC=3 PC=51
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    elif op == "RETI":    PC = stack.pop()       # return from interrupt
                               ~~~~~~~~~^^
IndexError: pop from empty list

The ISR ran, but RETI had no bookmark. A real CPU would jump to garbage.

Mini project: tiny CPU v2 (flags, JZ, a stack, CALL and RET)

We add an 8-bit ALU that sets Z, C, S, V (as in episode 3), JZ (jump if zero), JMP (always jump), and a stack with SP, CALL and RET. The program computes 6 + 6 with a loop that calls a subroutine (reusable code you CALL and that RETurns, like a function).

# tiny CPU v2: 8-bit ALU with a flag register, JZ/JMP, a stack with SP, CALL/RET
MASK = 0xFF

def alu(op, a, b):
    """8-bit ADD or SUB. Returns the result and the four flags."""
    cin = 0
    if op == "SUB":
        b, cin = ~b & MASK, 1                 # a - b = a + NOT b + 1
    total = a + b + cin
    r = total & MASK
    flags = {"Z": int(r == 0),                # zero
             "C": total >> 8,                 # carry out of bit 7
             "S": r >> 7,                     # sign = MSB
             "V": int(((a ^ r) & (b ^ r) & 0x80) != 0)}   # signed overflow
    return r, flags

for op, a, b in [("ADD", 200, 100), ("ADD", 100, 50), ("SUB", 5, 5), ("SUB", 3, 5)]:
    r, f = alu(op, a, b)
    print(f"{op} {a:>3},{b:>3} -> {r:>3}  Z={f['Z']} C={f['C']} S={f['S']} V={f['V']}")
print()

# program: total = 6 + 6, using a loop and a subroutine
mem = [0] * 32
mem[0:6] = ["LOAD 24", "JZ 7", "SUB 25", "STORE 24", "CALL 10", "JMP 0"]
mem[7] = "HALT"
mem[10:14] = ["LOAD 26", "ADD 27", "STORE 26", "RET"]      # subroutine: total += 6
mem[24], mem[25], mem[26], mem[27] = 2, 1, 0, 6            # count, one, total, step

PC, ACC, SP = 0, 0, 32               # stack is empty; it grows down from 31
F = {"Z": 0, "C": 0, "S": 0, "V": 0}

while True:
    IR = mem[PC]; PC += 1                        # fetch
    op, *arg = IR.split(); a = int(arg[0]) if arg else 0   # decode
    if op == "LOAD":
        ACC = mem[a]; F["Z"], F["S"] = int(ACC == 0), ACC >> 7
    elif op in ("ADD", "SUB"):
        ACC, F = alu(op, ACC, mem[a])
    elif op == "STORE": mem[a] = ACC
    elif op == "JMP":   PC = a
    elif op == "JZ" and F["Z"]: PC = a
    elif op == "CALL":
        SP -= 1; mem[SP] = PC; PC = a            # push return address
    elif op == "RET":
        PC = mem[SP]; SP += 1                    # pop it back
    elif op == "HALT": break
    flags = "".join(k for k in "ZCSV" if F[k]) or "-"
    print(f"{IR:9} ACC={ACC:<3} PC={PC:<2} SP={SP} flags={flags:<3} stack={mem[SP:32]}")

print("total =", mem[26])

Output:

ADD 200,100 ->  44  Z=0 C=1 S=0 V=0
ADD 100, 50 -> 150  Z=0 C=0 S=1 V=1
SUB   5,  5 ->   0  Z=1 C=1 S=0 V=0
SUB   3,  5 -> 254  Z=0 C=0 S=1 V=0

LOAD 24   ACC=2   PC=1  SP=32 flags=-   stack=[]
JZ 7      ACC=2   PC=2  SP=32 flags=-   stack=[]
SUB 25    ACC=1   PC=3  SP=32 flags=C   stack=[]
STORE 24  ACC=1   PC=4  SP=32 flags=C   stack=[]
CALL 10   ACC=1   PC=10 SP=31 flags=C   stack=[5]
LOAD 26   ACC=0   PC=11 SP=31 flags=ZC  stack=[5]
ADD 27    ACC=6   PC=12 SP=31 flags=-   stack=[5]
STORE 26  ACC=6   PC=13 SP=31 flags=-   stack=[5]
RET       ACC=6   PC=5  SP=32 flags=-   stack=[]
JMP 0     ACC=6   PC=0  SP=32 flags=-   stack=[]
LOAD 24   ACC=1   PC=1  SP=32 flags=-   stack=[]
JZ 7      ACC=1   PC=2  SP=32 flags=-   stack=[]
SUB 25    ACC=0   PC=3  SP=32 flags=ZC  stack=[]
STORE 24  ACC=0   PC=4  SP=32 flags=ZC  stack=[]
CALL 10   ACC=0   PC=10 SP=31 flags=ZC  stack=[5]
LOAD 26   ACC=6   PC=11 SP=31 flags=C   stack=[5]
ADD 27    ACC=12  PC=12 SP=31 flags=-   stack=[5]
STORE 26  ACC=12  PC=13 SP=31 flags=-   stack=[5]
RET       ACC=12  PC=5  SP=32 flags=-   stack=[]
JMP 0     ACC=12  PC=0  SP=32 flags=-   stack=[]
LOAD 24   ACC=0   PC=1  SP=32 flags=Z   stack=[]
JZ 7      ACC=0   PC=7  SP=32 flags=Z   stack=[]
total = 12
  • ALU tests: 200 + 100 = 300 doesn't fit 8 bits → 44, C = 1. 100 + 50 = 150 is -106 as a signed byte → V = 1, S = 1. 5 - 5 → Z = 1 (C = 1 after SUB means "no borrow"). 3 - 5 = 254 = -2 → S = 1, C = 0 (a borrow was needed).
  • CALL 10 pushes return address 5 (SP 32 → 31) and jumps; RET pops 5 back into PC (SP → 32).
  • LOAD sets only Z and S and leaves C alone, so the C from the last SUB stays visible, as on many real CPUs.
  • When the counter is 0, LOAD 24 sets Z, JZ 7 jumps to HALT, total = 12.
  • Try it: add PUSH x / POP x, a subroutine that CALLs another (watch two return addresses on the stack), or JC (jump if carry).

Practice

  1. Address lines for 4 GiB of byte-addressable memory?
  2. 24 address lines, byte-addressable. Maximum memory?
  3. 1 GiB, word-addressable with 32-bit words. Address lines?
  4. 2 MiB with 16-bit words, word-addressable. How many words and lines?
  5. Data-bus trips to move a 64-byte block over a 64-bit bus? Over a 16-bit bus?
  6. Clock period at 2.5 GHz? Clock rate if the period is 0.5 ns?
  7. 3 GHz, CPI 1.5, 6 × 10⁹ instructions. CPU time?
  8. Mix: ALU 40% (CPI 1), load 30% (CPI 4), store 20% (CPI 2), branch 10% (CPI 3). CPI? MIPS at 2 GHz?
  9. 4 × 10⁹ instructions, CPI 1.25. What clock rate gives 2 s?
  10. A new design raises the clock 20% but CPI rises 10%. Speedup?
  11. f = 0.6 sped up 3×. Overall speedup? Limit?
  12. f = 0.9. Maximum speedup? With s = 9?
  13. f = 0.9. What s gives an overall 5×?
  14. f = 0.5. Can you reach 3×?
  15. 64 mutually exclusive control signals: field width in vertical vs horizontal microcode?
  16. Control memory of 512 microinstructions, 72 bits each. Size?
  17. Write the RTN micro-operations for fetching and executing STORE 9.
  18. Just after fetching the instruction at address 5 (one word per instruction), what are PC and IR?
  19. An interrupt arrives while the instruction at 40 runs. Which address is pushed, and when is it serviced?
  20. The instruction set will change often during development. Hardwired or microprogrammed?
  21. Why are interrupts disabled while PC and flags are saved?
Solutions

Numbers computed with a Python 3.13 script; its output:

Q1  4 GiB byte-addressable: 32 lines
Q2  24 lines, byte-addressable: 16 MiB
Q3  1 GiB, 32-bit words: 28 lines
Q4  2 MiB with 16-bit words: 1048576 words, 20 lines
Q5  64-byte block on 64-bit bus: 8 trips; on 16-bit bus: 32
Q6  2.5 GHz period: 0.40 ns;  0.5 ns period -> 2 GHz
Q7  3 GHz, CPI 1.5, 6e9 instr: 3.00 s
Q8  CPI of mix: 2.30   MIPS at 2 GHz: 870
Q9  clock for 4e9 instr, CPI 1.25, 2 s: 2.50 GHz
Q10 clock +20%, CPI +10%: old 1.000 s new 0.917 s speedup 1.091
Q11 f=0.6, s=3: 1.67   limit: 2.50
Q12 f=0.9 limit: 10   with s=9: 5.00
Q13 f=0.9, want x5: s = 9
Q14 f=0.5, want x3: impossible (limit 2)
Q15 vertical microcode, 64 exclusive signals: 6 bits; horizontal: 64 bits
Q16 control memory 512 words x 72 bits: 36864 bits = 4 KiB +  512 bytes
  1. 2² × 2³⁰ = 2³² bytes → 32. 2. 2²⁴ bytes = 16 MiB. 3. 2³⁰ / 2² = 2²⁸ words → 28. 4. 2²¹ / 2 = 2²⁰ = 1,048,576 words → 20.
  2. 512 bits / 64 = 8; / 16 = 32. 6. 0.40 ns; 1 / 0.5 ns = 2 GHz. 7. 6 × 10⁹ × 1.5 / 3 × 10⁹ = 3 s.
  3. 0.4 + 1.2 + 0.4 + 0.3 = 2.30; 2000 / 2.3 ≈ 870 MIPS. 9. IC × CPI / time = 5 × 10⁹ / 2 = 2.5 GHz.
  4. New time = old × 1.10 / 1.20 → speedup 1.09. 11. 1 / (0.4 + 0.2) = 1.67; limit 2.5. 12. Limit 10; 1 / (0.1 + 0.1) = 5.
  5. 1/5 - 0.1 = 0.1 → s = 0.9 / 0.1 = 9. 14. No: the limit is 1 / 0.5 = 2. 15. Vertical 6 bits (2⁶ = 64), horizontal 64 bits.
  6. 36,864 bits = 4,608 bytes (4.5 KiB).
  7. T1: MAR ← PC; T2: MDR ← M[MAR], PC ← PC + 1; T3: IR ← MDR; T4: MAR ← IR(address) (= 9); T5: MDR ← ACC; T6: M[MAR] ← MDR (WRITE).
  8. PC = 6, IR = the instruction from address 5.
  9. The instruction at 40 finishes first; in the interrupt cycle 41 is pushed and PC ← the ISR address.
  10. Microprogrammed: changing an instruction means rewriting control memory, not the circuit.
  11. A second interrupt mid-save could overwrite a half-saved context, and the first program could never resume correctly.

Quick quiz

A byte-addressable memory is 256 MiB. How many address lines does the CPU need?

  • A. 8
  • B. 24
  • C. 28
  • D. 32
Answer

C, 28. 256 MiB = 2⁸ × 2²⁰ = 2²⁸ bytes, each needing its own address, so 28 lines (the bus program printed 256 MiB, byte-addressable -> 28 lines).

Interview questions

  • Main parts of a CPU? ALU (does the work), control unit (decides, sends control signals), registers (fast storage), joined to memory and I/O by the system bus.
  • PC vs IR? PC: address of the next instruction. IR: the instruction executing now.
  • What are MAR and MDR for? MAR holds the address of a memory access; MDR holds the data read or to be written.
  • Fetch cycle in RTN? T1: MAR ← PC; T2: MDR ← M[MAR], PC ← PC + 1; T3: IR ← MDR.
  • Address bus vs data bus? Address: which location, CPU → memory. Data: the value, both ways. Address width sets addressable memory; data width sets bits per transfer.
  • Polling vs interrupts? Polling keeps asking and wastes cycles; interrupts let the device signal when ready.
  • What happens on an interrupt? Finish the instruction, save PC and flags, disable interrupts, vector to the ISR, run it, restore, RETI.
  • Maskable vs non-maskable? Vectored? Maskable can be disabled; NMI can't. Vectored: the device's number indexes a vector table of ISR addresses.
  • Why a stack for return addresses? LIFO matches nesting: the latest call or interrupt returns first.
  • Hardwired vs microprogrammed? Hardwired: fixed gates, fast, hard to change (RISC). Microprogrammed: microinstructions in control memory, flexible, slower (CISC).
  • Is 4 GHz always faster than 3 GHz? No: time = IC × CPI ÷ clock rate.
  • Why is MIPS a poor measure? It ignores how much each instruction does; different instruction sets need different counts.
  • Amdahl's law and its limit? 1 ÷ ((1 - f) + f ÷ s), never above 1 ÷ (1 - f). Make the common case fast.

Glossary

Term Plain meaning Example
CPU The chip that runs programs: ALU + control unit + registers runs fetch-decode-execute
ALU (Arithmetic Logic Unit) CPU part that does arithmetic and logic ACC + MDR = 42
Control unit (CU) CPU part that reads instructions and sends control signals decodes ADD 8
Control signal One wire the control unit switches on to make a part act READ, WRITE, "ALU add"
Register Tiny, very fast storage box inside the CPU ACC, PC, IR
Flip-flop One-bit memory circuit (episode 5) 8 flip-flops = 8-bit register
Accumulator (ACC) Register holding the running result in a simple CPU ADD 8: ACC = ACC + mem[8]
General-purpose registers (GPRs) Registers that can hold any data R0, R1, R2
Register file The whole numbered set of GPRs 16 registers, 0 to 15
Program counter (PC) Address of the next instruction PC = 2 while address 1 runs
Instruction register (IR) The instruction being run now IR = ADD 8
MAR Memory Address Register: address of a memory access MAR = 7
MDR Memory Data Register: data read from or written to memory MDR = 25
Status / flag register Register holding the flags Z = 1 after 5 - 5
Flag One status bit set by the ALU Z, C, S, V
Zero flag (Z) 1 if the result was 0 5 - 5
Carry flag (C) 1 if a bit fell off the left end 200 + 100 in 8 bits
Sign flag (S / N) Copy of the result's MSB; 1 = negative 3 - 5 → S = 1
Overflow flag (V) 1 if a signed result has the wrong sign 100 + 50 → V = 1
Stack Memory used last in, first out return addresses
Push / pop Put a value on top / take the top value off CALL pushes 5
Stack pointer (SP) Register with the address of the stack top SP 32 → 31 on push
Memory / RAM Numbered boxes holding program and data mem[7] = 25
Address Number of a memory box 9 in STORE 9
Instruction One command the CPU understands LOAD 7
Opcode The "what to do" part LOAD
Operand The "on what" part 7 in LOAD 7
LOAD / STORE / HALT Memory → ACC / ACC → memory / stop STORE 9
Stored program / von Neumann design Program and data share one memory code at 0-3, data at 7-9
Fetch-decode-execute cycle (instruction cycle) Fetch at PC, decode, execute, repeat IR ← mem[PC], PC + 1 ...
Interrupt cycle Check after each instruction for a waiting interrupt push PC, PC ← 50
Micro-operation One tiny register-transfer step in one tick MAR ← PC
Register-transfer notation (RTN) Writing micro-operations as X ← Y with steps T1, T2 T3: IR ← MDR
Jump / branch Instruction that writes a new value into PC JMP 0
Conditional jump Jump taken only if a flag condition holds JNZ 0, JZ 7
Compare Subtract and keep only the flags if x == y → compare + JZ
Bus / system bus Shared set of wires / address + data + control buses CPU ↔ RAM
Address bus Carries the address, CPU → memory 32 lines → 4 GiB
Data bus Carries data, both directions 64-bit data bus
Control bus Read, write, clock, interrupt signals READ in T2
Bus width Number of wires in a bus 32-bit data bus
Addressable memory Locations nameable with n lines: 2ⁿ 16 lines → 64 KiB
Bus transfer (trip) One move of data-bus-width bits 8 bytes on 32 bits = 2 trips
Byte-addressable Each address names one byte 256 MiB → 28 lines
Word / word-addressable Fixed group of bytes / each address names one word 4 GiB, 4-byte words → 30 lines
KiB / MiB / GiB 2¹⁰ / 2²⁰ / 2³⁰ bytes 64 KiB = 65,536 bytes
KB / MB / GB 10³ / 10⁶ / 10⁹ bytes 4 GB = 4,000,000,000 bytes
Polling CPU repeatedly asks a device if it's ready checking the door every minute
Interrupt Device signal asking the CPU to stop and serve it a key press
Interrupt service routine (ISR) Small routine that serves an interrupt READKEY, RETI at 50
RETI Return from interrupt: pop PC, re-enable interrupts PC = 3 again
Context PC, flags, registers saved to resume later pushed before the ISR
Interrupt-enable flag / masking Bit allowing interrupts / clearing it to ignore maskable ones disabled while saving
Maskable interrupt Can be disabled keyboard
Non-maskable interrupt (NMI) Cannot be disabled; emergencies power failure
Vectored interrupt Device sends a number that selects its ISR device 2 → entry 2
Interrupt vector table Table of ISR start addresses entry 2 = 0x0400
Software interrupt / exception Interrupt from an instruction / from a CPU error system call / divide by zero
Subroutine / CALL / RET Reusable code / push PC and jump / pop PC CALL 10 ... RET
Hardwired control Control unit as a fixed gate circuit fast, RISC
Microprogrammed control Control unit stepping through microinstructions flexible, CISC
Microinstruction One control-memory word: signals for one tick signals for MAR ← PC
Control memory Small memory holding the microprograms 512 × 72 bits
Horizontal / vertical microcode One bit per signal / encoded short fields 64 bits vs 6 bits
RISC Few, simple instructions, mostly one cycle load/store architecture
CISC Many complex instructions memory-to-memory add
Clock / clock cycle Ticking timing signal / one tick T1, T2, T3
Clock rate Ticks per second 4 GHz
Hertz (Hz) / GHz One tick per second / 10⁹ per second 2.5 GHz
Clock period (cycle time) 1 / clock rate 4 GHz → 0.25 ns
Nanosecond (ns) 10⁻⁹ seconds 0.40 ns
Instruction count (IC) Instructions the program runs 2 × 10⁹
CPI Average clock cycles per instruction 1.2
Instruction mix / weighted CPI Share of each class / Σ(share × CPI) 1.70
CPU time equation IC × CPI ÷ clock rate 2e9 × 2 / 4e9 = 1 s
MIPS Millions of instructions per second = clock ÷ (CPI × 10⁶) 3333
Speedup Old time ÷ new time 1.00 / 0.60 = 1.67
Amdahl's law Overall speedup = 1 ÷ ((1 - f) + f ÷ s) f = 0.8, s = 4 → 2.5
Amdahl limit Maximum speedup 1 ÷ (1 - f) f = 0.8 → 5
Solving Amdahl for s s = f ÷ (1 ÷ target - (1 - f)) f = 0.8, 4× → s = 16

Summary

  • The ALU works, the control unit decides with control signals, and registers (ACC, GPRs in a register file, PC, IR, MAR, MDR, flags, SP) are the fastest storage.
  • PC = address of the next instruction, IR = current instruction. Forget PC ← PC + 1 and the CPU repeats forever.
  • Instruction cycle: fetch → decode → execute → interrupt cycle. Fetch in RTN: T1 MAR ← PC; T2 MDR ← M[MAR], PC ← PC + 1; T3 IR ← MDR.
  • System bus: address (one way), data (both ways), control. n address lines → 2ⁿ addresses; word-addressing divides by word size; data width sets bits per trip.
  • Flags Z, C, S, V describe the last result; ifs and loops are compare + conditional jump.
  • Interrupts beat polling: finish, save PC and flags, disable, vector to the ISR, restore, RETI. Maskable vs NMI; vectored interrupts use a vector table; the stack (LIFO, SP) holds return addresses.
  • Hardwired control is fast (RISC); microprogrammed is flexible (CISC); horizontal vs vertical microcode.
  • CPU time = IC × CPI ÷ clock rate; clock period = 1 / clock rate; mix CPI is a weighted average; MIPS = clock ÷ (CPI × 10⁶). GHz alone proves nothing.
  • Amdahl: 1 ÷ ((1 - f) + f ÷ s), capped at 1 ÷ (1 - f). Make the common case fast.

Next episode: Instruction set architecture and addressing modes. Which instructions exist, instruction formats, how an instruction says where its data is, RISC vs CISC in depth, and reading real assembly.