Foundations of ComputingVol. 1 · Part I
0 / 0

Shelves / Foundations of Computing

CS·07

Computer Architecture

What the hardware actually does with your code: the CPU's parts, the instruction cycle, pipelines and speculation, the memory hierarchy, interrupts and DMA, and the three instruction sets that matter today.

45 topics · ~46 min read · 41-question quiz
Updated Suggest a correction

Start here: how a computer actually runs your program

From switches to logic gates

At the very bottom, a processor is billions of transistors: tiny electrically-controlled switches. A switch is on or off, which is exactly a bit. Wire a few switches together and you get a logic gate, a circuit whose output bit depends on its input bits by a fixed rule. The rules are the truth tables from chapter 5:

Gate Output is 1 when… Example: inputs 1, 0
AND both inputs are 1 0
OR at least one input is 1 1
NOT the (single) input is 0 (NOT 1) = 0
XOR ("exclusive or") exactly one input is 1 1

That's all a computer is made of. Everything else is these gates, combined cleverly and in enormous numbers.

From gates to arithmetic: building an adder

Look at adding two single bits: 0+0 = 0, 0+1 = 1, 1+0 = 1, 1+1 = 10 (sum 0, carry 1). The sum bit is 1 when exactly one input is 1: that's XOR. The carry is 1 when both are 1: that's AND. A circuit that also takes an incoming carry is a full adder; chain four of them, passing each carry to the next, and you can add 4-bit numbers. Here it is in Python, using only AND, OR and XOR:

Python
AND = lambda a, b: a & b; OR = lambda a, b: a | b; XOR = lambda a, b: a ^ b
def full_adder(a, b, carry_in):
    s = XOR(XOR(a, b), carry_in)
    carry_out = OR(AND(a, b), AND(carry_in, XOR(a, b)))
    return s, carry_out
def add4(x, y):
    carry, out = 0, []
    for i in range(4):                     # from the lowest bit up, passing the carry along
        s, carry = full_adder((x >> i) & 1, (y >> i) & 1, carry)
        out.append(s)
    return sum(bit << i for i, bit in enumerate(out)), carry
Text
 6 +  7: 0110 + 0111 = 1101 with carry 0  → 13
 9 +  9: 1001 + 1001 = 0010 with carry 1  → 18
15 +  1: 1111 + 0001 = 0000 with carry 1  → 16

The last line is overflow from chapter 6, happening in hardware: four bits can't hold 16, so the answer wraps to 0000 and the carry "falls off" (the CPU records it in a flag that programs can check). A real 64-bit CPU's adder is the same idea with 64 stages and tricks to compute the carries faster.

The parts of a processor

CPU Control unitfetch, decode ALUadd, compare Registers: PC, ACC, … Clock: ticks billions of times a second Memory (RAM) 0: LOAD 101: ADD 112: ADD 123: STORE 13…10: 120 11: 8012: 150 13: ?program and data addressdata
A simple computer: the CPU fetches instructions and data from memory over the bus
  • Memory (RAM) is a long row of numbered boxes; each box's number is its address (chapter 3's picture). It holds both the program (instructions, encoded as numbers) and the data. Keeping both in the same memory is the stored-program idea (von Neumann, 1945), and it's why a program can be loaded, replaced or even generated while the machine runs.
  • Registers are a handful of very fast storage slots inside the CPU itself. The program counter (PC) holds the address of the next instruction; others hold the values being worked on.
  • The ALU (arithmetic logic unit) is the gate circuitry that adds, subtracts, compares and does bitwise operations, like the adder above.
  • The control unit reads each instruction and switches the right parts on.
  • The clock is a signal ticking at a fixed rate: a 3 GHz CPU ticks 3 billion times a second, and each step happens on a tick.

The fetch–decode–execute cycle

Every CPU, from a washing machine controller to a server processor, repeats one loop forever:

  1. Fetch the instruction at the address in the PC, and advance the PC.
  2. Decode it: which operation, on which registers or addresses?
  3. Execute it: let the ALU compute, read or write memory, or change the PC (a jump, which is how if and loops are made).

Here is a complete toy computer that does exactly this: 16 memory cells, one working register (the accumulator), a program counter and six instructions. Its program adds the numbers in cells 10, 11 and 12 and stores the total in cell 13:

Python
LOAD, ADD, STORE, JUMP_IF_ZERO, PRINT, HALT = range(6)
names = ["LOAD", "ADD", "STORE", "JZ", "PRINT", "HALT"]
memory = [0] * 16
program = [(LOAD, 10), (ADD, 11), (ADD, 12), (STORE, 13), (PRINT, 13), (HALT, 0)]
for i, ins in enumerate(program): memory[i] = ins          # the program is stored in memory, like data
memory[10], memory[11], memory[12] = 120, 80, 150           # the data
acc, pc, cycle = 0, 0, 0                                    # registers: accumulator, program counter
while True:
    cycle += 1
    op, addr = memory[pc]                                   # FETCH the instruction at pc
    pc += 1                                                 # point at the next one
    if op == LOAD:    acc = memory[addr]                    # DECODE and EXECUTE
    elif op == ADD:   acc = acc + memory[addr]
    elif op == STORE: memory[addr] = acc
    elif op == JUMP_IF_ZERO and acc == 0: pc = addr
    elif op == PRINT: print("    output:", memory[addr])
    print(f"cycle {cycle}: {names[op]:<5} {addr:>2}  → acc={acc:<4} pc={pc}")
    if op == HALT: break
Text
cycle 1: LOAD  10  → acc=120  pc=1
cycle 2: ADD   11  → acc=200  pc=2
cycle 3: ADD   12  → acc=350  pc=3
cycle 4: STORE 13  → acc=350  pc=4
    output: 350
cycle 5: PRINT 13  → acc=350  pc=5
cycle 6: HALT   0  → acc=350  pc=6

Read the trace slowly: it's the whole idea of a computer. Your C, Java or Python program is translated (chapter 10) into instructions like these, just more of them and more kinds. if becomes a comparison followed by a conditional jump that sets the PC elsewhere; a loop is a jump backwards; a function call is a jump that first saves where to come back to (on the stack, chapter 2). A real x86 or ARM CPU has hundreds of instructions and 16–32 general registers, and its instruction set architecture (ISA) is the precise list of them: the contract between hardware and software.

Why a real CPU is much faster than one instruction per tick

Modern CPUs don't do one instruction at a time. Like an assembly line, they pipeline: while one instruction executes, the next is decoded and a third fetched. They also run several instructions at once when they don't depend on each other, predict which way a branch will go before knowing, and run ahead speculatively. You don't need the details yet (the full-depth sections cover them); the practical lesson is that predictable code with independent steps runs fastest, and a mispredicted branch costs around 15–20 cycles.

Memory is slow; caches hide it

A CPU tick is about a third of a nanosecond, but fetching from RAM takes around 80–100 nanoseconds: hundreds of ticks of waiting. So CPUs keep small, fast copies of recently used memory in caches, organised in levels:

Interactive diagram: Why memory is slow and caches hide it. It needs JavaScript; the text around it says the same.
Level Typical size Typical time to read Analogy
Registers a few hundred bytes less than 1 ns what's in your hands
L1 cache 32–64 KB per core about 1 ns the open book on your desk
L2 cache 1–2 MB per core about 4 ns the shelf beside your desk
L3 cache tens of MB, shared about 10–15 ns the bookcase in your room
RAM GBs about 80–100 ns the library across town
SSD TBs about 100,000 ns ordering a book by post

Caches work because programs have locality: they tend to reuse what they just used (temporal locality) and use things near what they just used (spatial locality). Memory moves into cache in cache lines of 64 bytes at a time, so reading one number also brings its neighbours. The same work can therefore be fast or slow depending only on the order you touch memory. Summing a 4096 × 4096 grid of integers in C, row by row versus column by column:

C
for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) sum += grid[r][c];   /* row by row: neighbours in memory */
for (int c = 0; c < N; c++) for (int r = 0; r < N; r++) sum += grid[r][c];   /* column by column: jumps 16 KB each step */
Text
sum=33554432  row order 14.8 ms, column order 157.0 ms (10.6x slower)

Same additions, same answer, ten times slower, purely because the column order uses one number from each 64-byte line it loads and then jumps 16 KB away. This is why arrays usually beat linked lists in practice (chapter 3) and why "data-oriented" design matters. The lab measures your own machine's cache levels.

Multiple cores

A core is a complete fetch–decode–execute engine. Since around 2005, CPUs have gained speed mainly by adding cores rather than ticking faster (faster clocks made chips too hot). Four cores can run four instruction streams at once, but only if your program gives them separate work (threads, chapter 8 and Part on concurrency). A single-threaded program uses one core however many you have.

Check yourself

How deep to go in computer architecture

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.

Level What you can do
L1 Name the CPU's parts and the memory hierarchy
L2 Write code that respects locality and avoids obvious hardware hazards
L3 Explain pipelines, branch prediction, out-of-order execution, caches and coherence, virtual-memory hardware
L4 Diagnose hardware-level performance problems with counters and profilers (cache misses, mispredictions, false sharing)
L5 Choose data layouts, algorithms and instance types with the hardware in mind (AoS vs SoA, x86 vs ARM servers)
L6 Operate fleets with hardware awareness: NUMA, CPU generations, speculative-execution mitigations, cost per instruction

The machine at a glance

The von Neumann model

Almost every computer follows the stored-program design described by John von Neumann in 1945: instructions and data live in the same memory, and a processor repeatedly fetches an instruction, works out what it means, and executes it. Treating code as data is what lets a program load another program, a compiler write machine code, or a JIT generate code at run time. It's also why buffer overflows can inject code, and why modern systems mark memory pages as either writable or executable but not both (W^X).

The main components:

CPU core control unitfetch / decode ALU / FPU / SIMDexecute registers: rip, rsp, rax…r15, xmm/zmm~1 cycle L1 I + L1 D32–64 KB · ~4 cyc L21–2 MB · ~14 cyc L3 (shared)8–100+ MB · ~40 cyc memory controller DRAM~80 ns PCIe root NVMe NIC GPU DMA
A simplified computer. The CPU talks to memory and devices over interconnects; caches sit between the core and DRAM.
  • CPU (central processing unit): executes instructions. A modern chip has several cores, each a full CPU, often with two hardware threads each (SMT, Hyper-Threading).
  • Memory (DRAM): large (GBs), slow relative to the CPU (~80 ns), volatile.
  • Caches: small, fast SRAM copies of recently used memory, inside the CPU.
  • Interconnects (buses): carry addresses, data and control signals between parts.
  • I/O devices: storage, network, graphics, attached over PCIe and reached through memory-mapped registers and DMA.

Clock, cycles and performance

A CPU's work is paced by a clock. At 4 GHz, one cycle lasts 0.25 ns, about the time light takes to travel 7.5 cm. Performance comes from three factors:

Text
time = instructions × (cycles per instruction) × (seconds per cycle)
     = IC × CPI × 1/f
  • Instruction count (IC) depends on your algorithm, language and compiler.
  • Cycles per instruction (CPI), or its inverse IPC (instructions per cycle), depends on the microarchitecture and on stalls: cache misses and branch mispredictions. Modern cores can sustain IPC of 4–6 on friendly code and drop below 0.1 when chasing cache misses.
  • Frequency stopped rising around 2005 at roughly 3–5 GHz. Power grows with frequency × voltage², and higher frequencies need higher voltage, so chips hit the power wall. Since then, performance has come from doing more per cycle (wider cores) and from more cores, which is why concurrency (chapter 8) became everyone's problem.

The lesson for software is that once your algorithm is right, memory access patterns and branch predictability decide most of the remaining speed.

Inside the CPU

The ALU

The arithmetic logic unit performs the actual computation: integer add, subtract, AND, OR, XOR, shifts and comparisons. It's built from the gates in chapter 5. An adder chains full adders (with carry-lookahead logic for speed), and subtraction reuses the adder with two's complement (chapter 6). A modern core has several ALUs plus:

  • Multipliers and dividers: multiply takes about 3 cycles, and integer divide 10–40+ cycles. That's why compilers replace x / 10 by a multiplication with a "magic" reciprocal and a shift, and why x % 2ⁿ becomes x & (2ⁿ−1) for unsigned values.
  • FPU: IEEE 754 floating point (chapter 6).
  • SIMD / vector units: one instruction operates on many values at once (covered under superscalar execution below).

Each ALU operation also sets flags (condition codes): Zero, Sign/Negative, Carry (unsigned overflow), Overflow (signed overflow). Conditional branches test these flags. if (a < b) compiles to a cmp that sets the flags and a jl (jump if less) that reads them.

Registers

Registers are the CPU's working storage: a few dozen named slots holding one word each and readable in a single cycle. Everything flows through them. x86-64 has 16 general-purpose 64-bit registers (rax rbx rcx rdx rsi rdi rbp rsp r8–r15) plus vector registers (xmm0–15, 128-bit; ymm 256-bit; zmm0–31 512-bit with AVX-512). ARM64 has 31 general-purpose registers (x0–x30, with w0–w30 naming their low 32 bits), plus a zero register and sp. RISC-V has 32 (x0 is hard-wired to zero).

Register sub-names in x86 reveal its history: rax (64-bit) contains eax (32-bit), which contains ax (16-bit), which splits into ah/al (8-bit). This goes back to the 8086 of 1978.

The register allocator in a compiler assigns your variables to these few registers (graph colouring, chapter 5). When there are more live values than registers, some get spilled to the stack, which costs memory accesses. Inside the chip there are far more physical registers (around 200–300 integer registers on recent cores) than architectural ones. Register renaming maps the architectural names onto them so that independent instructions can run in parallel (covered under out-of-order execution below).

Instruction pointer and stack pointer

Two registers have special jobs:

  • The instruction pointer (rip on x86-64, pc on ARM and RISC-V) holds the address of the next instruction. Fetch reads from it, and normally it advances by the instruction's length. Jumps, branches, calls and returns write it. rip-relative addressing (load data at an offset from the current instruction) is what makes code position-independent, which matters for shared libraries and ASLR (chapter 10).
  • The stack pointer (rsp, sp) points to the top of the current thread's call stack. On x86-64 the stack grows downward (toward lower addresses). push decrements rsp and stores, pop loads and increments, call pushes the return address and jumps, and ret pops it into rip.

Here is what a function call looks like in memory, with System V AMD64 conventions (Linux, macOS):

high addresses caller's frame (main) return address → main saved rbp (main's) f's locals, spilled regse.g. int x at [rbp−4] return address → f g's frame… low addresses (stack grows ↓) rbp of f (frame pointer) rsp (top of stack) args 1–6 travel in rdi rsi rdx rcx r8 r9 return value in rax rsp must be 16-byte aligned at call callee-saved: rbx rbp r12–r15 caller-saved: rax rcx rdx rsi rdi r8–r11
A stack frame for f(a, b) calling g. The stack grows downward. Each frame holds the return address, the saved frame pointer and locals.
C
int square(int x) { return x * x; }
int main(void) { return square(7); }
x86-64 asm
; gcc -O0 output (lightly trimmed, Intel syntax) — what the code does at the machine level
square:
    push    rbp              ; save caller's frame pointer
    mov     rbp, rsp         ; set up our frame
    mov     DWORD PTR [rbp-4], edi   ; spill argument x (arrived in edi) to the stack
    mov     eax, DWORD PTR [rbp-4]
    imul    eax, eax         ; x * x → eax (return register)
    pop     rbp
    ret                      ; pop return address into rip
main:
    push    rbp
    mov     rbp, rsp
    mov     edi, 7           ; first argument in edi
    call    square           ; push return address, jump
    pop     rbp
    ret
; With -O2 the whole program becomes:  main: mov eax, 49 / ret

The -O2 version shows why you should benchmark optimised builds only. The compiler inlined square and folded the constant.

Control unit and the instruction cycle

The control unit orchestrates everything: it decodes each instruction and drives the datapath. Conceptually, every instruction goes through the same cycle:

  1. Fetch: read the instruction bytes at rip from the instruction cache.
  2. Decode: work out the operation, operands and addressing mode. On x86 the instruction length is variable (1–15 bytes), so decoding is hard work. Modern x86 cores translate instructions into simpler internal micro-ops (µops) and cache the decoded µops in a µop cache. ARM64 and RISC-V use fixed 4-byte instructions (RISC-V also has 2-byte compressed ones), which makes decoding much simpler.
  3. Execute: the ALU or another unit computes the result, or computes a memory address.
  4. Memory access: load from or store to memory, if the instruction does that.
  5. Write-back: write the result to the destination register and update flags.

Memory and buses

Memory: addresses, words and DRAM

Memory is a huge array of bytes indexed by addresses. On x86-64, addresses are 64-bit values, but only 48 bits (256 TB) or 57 bits (with 5-level paging) are actually used. DRAM stores each bit as charge in a tiny capacitor that leaks, so every row must be refreshed every ~64 ms. Reading a bit drains it, so the row must be written back.

DRAM is organised in banks, rows and columns. Reading a new row (activate, read, precharge) is slow. Reading more columns from an already open row is fast. Combined with the CPU fetching whole 64-byte cache lines, this makes sequential access dramatically faster than random access at every level of the hierarchy. Bandwidth can reach 50–100+ GB/s per socket, while random-access latency stays around 80–100 ns. Latency hasn't improved much in 20 years, whereas bandwidth has.

The memory hierarchy exists because no technology is fast, large and cheap at once:

Level Typical size Latency Technology Managed by
Registers ~1 KB 0–1 cycle Flip-flops Compiler
L1 cache 32–64 KB per core (×2: instruction + data) ~4–5 cycles (~1 ns) SRAM Hardware
L2 cache 0.5–3 MB per core ~12–16 cycles (~3–4 ns) SRAM Hardware
L3 cache 8–100+ MB shared ~40–70 cycles (~10–20 ns) SRAM Hardware
DRAM 8 GB–TBs ~200–400 cycles (~60–100 ns) Capacitors OS (virtual memory)
NVMe SSD TBs ~20–100 µs NAND flash OS / filesystem
HDD TBs ~5–10 ms Spinning platters OS
Network storage ∞ ~0.5 ms+ Remote Application

Buses and interconnects

A bus is a shared set of wires carrying addresses, data and control signals. Classic textbook machines had one system bus. Modern systems use point-to-point links and on-chip networks:

  • On-chip interconnects (ring buses, meshes, AMD's Infinity Fabric) connect cores, cache slices and memory controllers.
  • Memory channels (DDR5) connect the memory controller to DIMMs. More channels give more bandwidth.
  • PCI Express (PCIe): serial lanes (×1, ×4, ×16) to devices. A PCIe 5.0 ×16 slot carries about 64 GB/s each way.
  • Multi-socket links (Intel UPI, AMD Infinity Fabric): connect CPU sockets. Memory attached to the other socket is slower to reach. This is NUMA (non-uniform memory access), and on big servers it matters. Databases and the JVM (-XX:+UseNUMA) try to allocate memory on the node where the thread runs.
  • CXL (Compute Express Link): newer, cache-coherent memory and device expansion over PCIe.

Interrupts

The CPU can't spend all its time asking devices whether something has happened (polling). Instead, devices raise an interrupt: a hardware signal that makes the CPU pause the current instruction stream, save minimal state, and jump to an interrupt handler (interrupt service routine) registered in a table, the IDT on x86. When the handler finishes, the CPU resumes exactly where it stopped. Kinds of interrupts:

Kind Source Example
Hardware interrupt (IRQ) Device Network packet arrived, disk read finished, key pressed, timer tick
Exception / fault The CPU, caused by the current instruction Page fault, divide by zero, invalid opcode, general protection fault
Trap / software interrupt Deliberate instruction System calls (syscall on x86-64, svc on ARM64), breakpoints (int3)
Inter-processor interrupt (IPI) Another core TLB shootdown, rescheduling a thread on another core

The timer interrupt is what makes preemptive multitasking possible. Every few milliseconds, the timer fires, the kernel's scheduler runs, and it can switch to another thread even if the current one never yields (chapter 8). Page faults (chapter 8) are how virtual memory loads pages lazily. Under heavy network load, taking one interrupt per packet would overwhelm the CPU, so NICs coalesce interrupts, and Linux NAPI switches to polling when traffic is busy.

DMA

Copying a 1 MB disk read into memory one word at a time would waste millions of CPU cycles. Direct memory access lets a device read or write main memory itself. The CPU programs the device with "transfer this many bytes to this physical address," goes off to do other work, and gets an interrupt when the transfer is done. NVMe SSDs, network cards and GPUs all use DMA, usually through ring buffers of descriptors in memory shared with the device (chapter 3's ring buffer again).

Two refinements matter in production:

  • An IOMMU translates device addresses like an MMU translates CPU addresses. It stops a buggy or malicious device from writing anywhere in memory, and it's required when passing devices through to VMs.
  • Zero-copy I/O avoids extra copies between kernel and user buffers. sendfile() lets the kernel DMA file pages straight to the NIC. Kafka's fast consumer reads rely on it, and so does Nginx static file serving. RDMA and io_uring's registered buffers go further.

The MMU and virtual memory (hardware side)

Every address a program uses is a virtual address. The memory management unit (MMU), part of each core, translates it to a physical address on every access, using page tables that the OS sets up. Memory is divided into pages, usually 4 KB (with 2 MB and 1 GB "huge pages" available).

Text
48-bit virtual address on x86-64 (4-level paging, 4 KB pages):
| PML4 index (9) | PDPT index (9) | PD index (9) | PT index (9) | page offset (12) |
   each 9-bit index selects one of 512 entries in a 4 KB table; the offset is unchanged

A full translation walks four tables, which would mean four memory accesses before the real one. The TLB (translation lookaside buffer), a small cache of recent translations, makes that rare: a TLB hit takes about one cycle. Each page table entry also carries permission bits (present, writable, user-accessible, no-execute), so the MMU enforces memory protection in hardware. Touching an unmapped page or violating permissions raises a page fault exception, and the OS decides what happens next.

That's the hardware half of virtual memory. Chapter 8 covers the OS half: what the kernel does with page faults, why processes are isolated, mmap, swapping, copy-on-write, and huge pages.

The CPU pipeline

Instruction fetch

The front end of the core keeps instructions flowing. Each cycle it fetches a block of bytes (16–64) from the L1 instruction cache at the address the branch predictor says comes next. It doesn't wait to find out whether the previous instruction was a branch. A miss in the instruction cache stalls the whole pipeline. Large codebases with poor code locality (huge Java or C++ services, deep virtual call chains) can spend a noticeable share of their cycles waiting on instruction fetch. That's why profile-guided optimisation (PGO) and post-link optimisers like BOLT reorder functions so hot code sits together. They commonly win 5–20% on big binaries.

Decode

Decode turns instruction bytes into the operations the back end executes. For x86 this is expensive. Instructions are 1–15 bytes long with prefixes, so finding where each one starts is itself work. Intel and AMD cores decode four to six instructions per cycle into micro-ops and keep a µop cache of already-decoded instructions so hot loops skip decoding entirely. Macro-fusion joins common pairs, such as cmp + jne, into one µop. Fixed-width ARM64 instructions decode in parallel easily, which is one reason Apple's M-series cores decode eight or more instructions per cycle.

Execute

The back end issues µops to execution units (several integer ALUs, load units, store units, branch units, and vector/FP units) once their inputs are ready, then retires (commits) them in program order. Loads go through the load-store unit, which translates addresses through the TLB, looks up the L1 data cache, and forwards values from earlier stores still in flight (store-to-load forwarding).

Pipelining

Doing one instruction start to finish before beginning the next would leave most of the circuit idle. Pipelining overlaps the stages, the way a laundry runs the washer, dryer and folding at the same time on different loads:

cycle 123456789 i1i2i3i4i5 IF ID EX MEM WB IF ID EX MEM WB IF ID EX MEM WB IF ID EX MEM WB IF ID EX MEM WB
A classic 5-stage pipeline. Once full, one instruction completes every cycle even though each takes 5 cycles.

Pipelining improves throughput (instructions completed per cycle), not latency (one instruction still takes all its stages). Modern pipelines have 14–20 stages. That depth lets each stage be simple and the clock fast, but it has a cost: anything that disrupts the flow wastes many cycles of work. The disruptions are called hazards:

  • Data hazards: an instruction needs a result that isn't ready yet (add rax, rbx followed by mul rcx, rax). Forwarding (bypassing) passes results straight from one execution unit to the next without waiting for write-back. A load followed immediately by its use still stalls for the cache latency.
  • Control hazards: the CPU doesn't know which instruction comes after a branch until the branch executes, perhaps 15 stages later. Waiting would waste those cycles on every branch, and about one instruction in five is a branch. The solution is to guess, which is the next topic.
  • Structural hazards: two instructions need the same unit in the same cycle. More units fix that.

Branch prediction

The branch predictor guesses the outcome and target of every branch before it executes, and the CPU speculatively fetches and executes along the guessed path. If the guess was right, no time is lost. If it was wrong, the speculative work is thrown away and fetching restarts from the right address. That misprediction penalty is roughly 15–20 cycles on modern cores.

Modern predictors (TAGE-like designs, perceptron predictors) look at the branch's address and the history of recent branch outcomes. They're right more than 95–99% of the time on typical code. They also predict targets of indirect jumps (virtual calls, switch jump tables) with a branch target buffer, and predict returns with a return stack buffer.

The famous demonstration (a well-known Stack Overflow question) is summing the elements of an array that are ≥ 128:

C
for (size_t i = 0; i < n; i++)
    if (data[i] >= 128) sum += data[i];
// random data:  the branch is a coin flip → ~50% mispredicted
// sorted data:  false…false, true…true → nearly perfect prediction
// sorted is about 3–6× faster for the SAME work.

Ways to cope with unpredictable branches:

  • Make data predictable: sort it, partition it, or process similar items together.
  • Go branchless: compute both results and select one. sum += (data[i] >= 128) * data[i]; or a mask such as -(x >= 128) & x. Compilers emit conditional moves (cmov on x86, csel on ARM) or SIMD blends for simple cases at -O2.
  • Give hints: __builtin_expect and C++20 [[likely]]/[[unlikely]], Rust #[cold] and std::hint::cold_path, Zig @branchHint(.unlikely). These mainly affect code layout, keeping the hot path straight and the cold path out of the way.
  • Use PGO: the compiler learns real branch frequencies from a training run.

The JVM gets a similar effect automatically. The JIT profiles branches while code runs in the interpreter, lays out the compiled code with the hot path first, and can even drop never-taken branches, adding an "uncommon trap" that deoptimises if one is ever taken (chapter 10).

Superscalar and SIMD execution

A superscalar core issues several instructions per cycle to parallel execution units. A recent wide x86 or ARM core can retire six to eight or more µops per cycle. Exploiting that instruction-level parallelism (ILP) needs independent instructions. A long chain where each operation depends on the previous one runs at the speed of the chain, however wide the core is.

C
// One dependency chain: every add waits for the previous one (~4 cycles each for FP add)
double s = 0;
for (size_t i = 0; i < n; i++) s += a[i];

// Four independent accumulators: four chains in flight at once → up to ~4× faster
double s0 = 0, s1 = 0, s2 = 0, s3 = 0;
for (size_t i = 0; i + 3 < n; i += 4) { s0 += a[i]; s1 += a[i+1]; s2 += a[i+2]; s3 += a[i+3]; }
double s = (s0 + s1) + (s2 + s3);   // (handle the remainder too)
// Compilers won't do this for floats on their own: it changes rounding (chapter 6).
// With -ffast-math, or for integers, they will, and they'll vectorise as well.

SIMD (single instruction, multiple data) adds parallelism within one instruction. A 256-bit AVX2 register holds eight f32 values, and one vaddps adds all eight pairs. On x86 the families are SSE (128-bit), AVX/AVX2 (256-bit) and AVX-512 (512-bit). ARM has NEON (128-bit) and SVE/SVE2 (length-agnostic). RISC-V has the vector extension "V". Compilers auto-vectorise simple loops: contiguous arrays, no aliasing, no complex control flow. When they can't, you can write SIMD explicitly:

Portable SIMD Intrinsics
C/C++ std::experimental::simd, C++26 std::simd, Highway, xsimd <immintrin.h> (_mm256_add_ps), <arm_neon.h>
Rust std::simd (nightly), wide, pulp crates std::arch::x86_64::*
Zig @Vector(8, f32): built into the language, with ordinary operators asm
Go none in the language; the Go team has been working on an experimental SIMD package for amd64 assembly files (Go's own assembler)
Java Vector API (jdk.incubator.vector, incubating since JDK 16, waiting on Valhalla) none (the JIT auto-vectorises loops)
Zig
// Zig: SIMD as a first-class type
const V = @Vector(8, f32);
fn dot(a: []const f32, b: []const f32) f32 {
    var acc: V = @splat(0);
    var i: usize = 0;
    while (i + 8 <= a.len) : (i += 8) {
        const va: V = a[i..][0..8].*;
        const vb: V = b[i..][0..8].*;
        acc += va * vb;                     // 8 multiplies and 8 adds per iteration
    }
    var sum = @reduce(.Add, acc);
    while (i < a.len) : (i += 1) sum += a[i] * b[i];   // remainder
    return sum;
}

SIMD underlies JSON parsers (simdjson parses gigabytes per second), string search (memchr), hashing, compression, image and audio codecs, database scans (columnar engines evaluate filters 16 or 32 values at a time), and ML inference on CPUs.

Out-of-order execution and speculation

An in-order core stalls whenever the next instruction isn't ready, for example while waiting 300 cycles for a cache miss. An out-of-order (OoO) core keeps going with later independent instructions:

  1. Instructions are fetched and decoded in order.
  2. Register renaming maps architectural registers onto a large physical register file. This removes false dependencies, where two instructions reuse the same register name for unrelated values.
  3. µops wait in a scheduler (reservation stations) and dispatch as soon as their inputs are ready, in whatever order that happens.
  4. A reorder buffer (ROB) with several hundred entries tracks everything in flight. Results retire in program order, so exceptions are precise and the program can't observe the reordering within a thread.

Out-of-order execution lets one core keep several cache misses in flight (memory-level parallelism) and hide latency. That's why independent loads, such as walking several linked lists at once, are much faster than one dependent chain.

Execution combined with branch prediction is speculative. The CPU executes instructions down a predicted path before knowing whether they should run at all. Architecturally, wrong-path work is discarded. Microarchitecturally, it can leave traces, mainly in which lines are now in the cache. Spectre and Meltdown (2018) exploited exactly this: speculatively read a secret, use it to index an array, roll back, then time cache accesses to recover the secret. The mitigations (kernel page-table isolation, retpolines, speculation barriers, site isolation in browsers, and SharedArrayBuffer restrictions) cost real performance and changed browser architecture (chapter 18).

Caches

L1, L2 and L3

A cache keeps copies of recently used memory in fast SRAM close to the core. A typical modern core has:

  • L1: split into L1i (instructions) and L1d (data), 32–64 KB each, private per core, ~4–5 cycles. It can serve two or three loads per cycle.
  • L2: unified, private, 0.5–3 MB, ~12–16 cycles.
  • L3 (last-level cache, LLC): shared by all cores on a die or chiplet, tens of MB, ~40–70 cycles. AMD's X3D chips stack extra L3 vertically (96 MB+), which helps games and some databases a lot.

When a load misses in L1, the request goes to L2, then L3, then DRAM. Each level is roughly 3–10× slower and larger than the one above it. Use lscpu, lstopo, or getconf -a | grep CACHE to see your machine's cache sizes.

Cache lines, associativity and replacement

Caches don't store individual bytes. They store cache lines (blocks) of 64 bytes on x86 and most ARM chips. Apple's M-series cores use 128-byte lines. Reading one byte loads its whole line. Each memory address splits into three fields:

Text
| tag | set index | offset within line (6 bits for 64-byte lines) |
  • The offset picks the byte within the line.
  • The set index picks which set of the cache the line can live in.
  • The tag identifies which of the many lines mapping to that set is present.

Associativity is how many places a line can go. In a direct-mapped cache, each address has exactly one slot. That's fast, but two hot addresses that map to the same slot keep evicting each other (conflict misses). In an N-way set-associative cache, a line can sit in any of N ways within its set. L1 caches are typically 8–12-way. When a set is full, a replacement policy chooses a victim: approximate LRU, tree-PLRU, or modern adaptive policies.

The three kinds of miss (the "3 Cs"):

  1. Compulsory: first touch of a line. Reduce these with prefetching and larger, sequential accesses.
  2. Capacity: the working set is bigger than the cache. Reduce these by blocking or tiling: process data in cache-sized chunks. Blocked matrix multiplication is the classic example, often 5–10× faster than the naive triple loop.
  3. Conflict: too many hot lines map to the same set. Strides that are powers of two are the usual cause. For example, walking the columns of a matrix whose row length is 4096 bytes makes every access land in the same few sets. Padding rows breaks the pattern.

Writes: modern caches are write-back. A store modifies the line in cache, marks it dirty, and writes it to memory only when it's evicted. Write-allocate means a store miss first loads the line. Streaming stores (movntdq) bypass the cache for large writes you won't read back soon.

Hardware prefetchers detect sequential and strided access patterns and fetch lines before you ask for them. They can't predict pointer chasing (chapter 3). Software prefetch is available (__builtin_prefetch, _mm_prefetch) but rarely beats the hardware.

Locality, measured

Everything above says one thing: access memory in the order it's laid out, and reuse data while it's still cached. Some ways to see the effect yourself:

Terminal
$ perf stat -e cycles,instructions,cache-misses,branch-misses ./program
   2,431,882,012  cycles
   3,915,221,409  instructions        #  1.61  insn per cycle
      41,281,773  cache-misses
       2,113,402  branch-misses

$ valgrind --tool=cachegrind ./program     # simulated per-line cache stats

Typical data-layout wins:

Pattern Problem Fix
Array of large structs, loop touches 2 fields Loads mostly unused bytes Struct of arrays (chapter 2: data-oriented design)
List<Integer> / []*T / Vec<Box<T>> Pointer chasing to boxed elements int[], []T, Vec<T> (store values inline)
Column-wise walk of a row-major matrix Stride of one row per access Swap loop order, or transpose first
Hash map with linked chains Miss per chain node Open addressing / Swiss tables (chapter 3)
Binary search over a huge sorted array Every probe a miss Eytzinger (BFS) layout or a B-tree with cache-line nodes
Tree of small heap nodes Random addresses Arena or index-based allocation (nodes near each other)

Cache coherence

Each core has its own L1 and L2. If core 0 writes x while core 1 holds a cached copy of x, core 1's copy is now stale. Cache coherence protocols keep all copies consistent in hardware. The classic one is MESI, where each line in each cache is in one of four states:

State Meaning
Modified Only this cache has it, and it's dirty (differs from memory)
Exclusive Only this cache has it, and it's clean. It can be written without telling anyone
Shared Several caches may have clean copies. A write must first invalidate the others
Invalid Not present or stale

To write a line in state S, a core broadcasts an invalidate, and every other copy goes to I. When another core then reads the line, the owner supplies the data (and writes it back if dirty). Real chips use extensions (MOESI, MESIF) and directories or snoop filters so they don't broadcast to every core.

Coherence makes caches invisible for correctness. The programmer never sees a stale value of a single location, once the write has actually reached the cache. It is not free for performance: a line that several cores write ping-pongs between their caches, and each transfer costs tens to hundreds of cycles. That's the root of the next problem.

False sharing

False sharing happens when two threads write different variables that happen to sit on the same cache line. Logically they share nothing. Physically, every write invalidates the other core's copy of the whole line, so the line bounces back and forth and both threads slow down, sometimes by 10× or more.

core 0: a++ in a loopL1: line in M state core 1: b++ in a loopL1: line invalidated a b rest of the 64-byte line the line ping-pongs on every write
Two counters 8 bytes apart share one 64-byte cache line. Each increment by one core invalidates the line in the other core's cache.
Java
// Per-thread counters packed into an array: false sharing
long[] counts = new long[nThreads];          // 8 longs fit in one cache line
// thread i: for (...) counts[i]++;         → very slow under contention

// Fixes: pad each counter to its own line, or accumulate locally and publish once
long local = 0;
for (...) local++;
counts[i] = local;                           // one write at the end
// The JDK uses @jdk.internal.vm.annotation.Contended (padding) in LongAdder, ForkJoinPool,
// ConcurrentHashMap's counter cells and Thread's fields for exactly this reason.

The fixes in other languages: C++17 alignas(std::hardware_destructive_interference_size) (usually 64), Rust crossbeam_utils::CachePadded<T> or #[repr(align(128))] (128 also covers adjacent-line prefetching on Intel and Apple's 128-byte lines), Go pads struct fields (_ [56]byte) or uses golang.org/x/sys/cpu.CacheLinePad, and Zig uses align(std.atomic.cache_line). Better still is to avoid sharing mutable state at all: per-thread accumulation, sharded counters (LongAdder), and message passing.

Instruction sets

ISA versus microarchitecture

The instruction set architecture (ISA) is the contract between software and hardware: the instructions, registers, memory model, privilege levels and exception behaviour. The microarchitecture is one particular implementation of that contract: pipeline depth, cache sizes, how many ALUs. One ISA (x86-64) has many microarchitectures (Intel Golden Cove, AMD Zen 5), all running the same binaries at different speeds. Compilers can target a baseline ISA (-march=x86-64-v2) for portability, or a specific level (-march=x86-64-v3 adds AVX2 and FMA) for speed.

CISC versus RISC is mostly a historical distinction now:

  • CISC (complex instruction set computer), like x86: many instructions, variable length, memory operands in arithmetic (add rax, [rbx+8]), instructions that do a lot (rep movsb copies a whole buffer).
  • RISC (reduced instruction set computer), like ARM, RISC-V, MIPS and POWER: fewer, simpler, fixed-length instructions, and a load-store design where only loads and stores touch memory and arithmetic works on registers only.

Modern x86 cores translate CISC instructions into RISC-like µops internally, and modern ARM cores are huge out-of-order machines. The ISA still matters for decode width, power, code density and licensing, but microarchitecture and process technology dominate performance.

x86-64

x86-64 is Intel's x86 lineage (the 8086 of 1978, through 32-bit IA-32), extended to 64 bits by AMD in 2003 (AMD64, which Intel then adopted). It's the standard for desktops, most servers and cloud instances, and Windows.

  • 16 general-purpose 64-bit registers, rip-relative addressing, SSE2 as the baseline floating-point unit (the old x87 stack is legacy).
  • Variable-length instructions (1–15 bytes), many addressing modes, and decades of extensions (SSE, AVX, AVX-512, AES-NI, SHA, BMI, AMX for matrix maths).
  • A relatively strong memory model (TSO).
  • Microarchitecture levels: v1 (baseline 2003), v2 (SSE4.2, POPCNT; ~2009), v3 (AVX2, FMA, BMI; ~2013–2015), v4 (AVX-512). RHEL 9 requires v2, and RHEL 10 requires v3.
  • Two syntaxes for the same assembly: AT&T (GNU default: movq %rsp, %rbp, source first, % and $ sigils) and Intel (mov rbp, rsp, destination first). Compiler Explorer and objdump -M intel let you choose.

ARM64

ARM (originally Acorn RISC Machine, 1985) licenses its ISA and core designs rather than making chips. AArch64 (ARMv8-A, 2011, and later ARMv9) is the 64-bit architecture. It runs nearly every phone, Apple Silicon Macs, AWS Graviton, Azure Cobalt, Google Axion, Ampere servers and NVIDIA Grace.

  • 31 general-purpose registers, fixed 4-byte instructions, load-store design.
  • A weak memory model, with explicit barriers (dmb, ldar/stlr acquire and release loads and stores).
  • NEON (128-bit SIMD) everywhere, and SVE/SVE2 (scalable vectors whose length the hardware decides, 128 to 2048 bits) on newer server cores.
  • Built-in security features: pointer authentication (PAC), branch target identification (BTI), and memory tagging (MTE) to catch use-after-free in hardware.
  • It is typically much more power-efficient per unit of work. Cloud ARM instances are often 20–40% cheaper for the same throughput, which is why "build multi-arch container images" (linux/amd64 + linux/arm64) is now standard DevOps practice (Part VII).

RISC-V

RISC-V (UC Berkeley, 2010) is an open, royalty-free ISA. Anyone can implement it without a licence. It's designed as a small base plus optional extensions:

  • RV64I: the base 64-bit integer ISA, about 50 instructions. Extensions add M (multiply/divide), A (atomics), F/D (float and double), C (compressed 2-byte instructions), and V (vectors, length-agnostic like SVE). RV64GC ("general") bundles the common set. The RVA23 profile defines what a Linux-capable application processor must support, including the vector extension.
  • 32 registers, with x0 hard-wired to zero, which simplifies many instructions (mov is addi rd, rs, 0).
  • A clean, regular encoding that's very easy to decode and to teach. If you want to learn assembly or write an emulator or compiler backend, it's an excellent first target.
  • Today it's widespread in microcontrollers and embedded cores (including inside other companies' chips: SSD controllers, GPUs' management cores), increasingly in Linux-capable boards, and an emerging option for servers and AI accelerators.

Reading assembly from your language

You don't need to write assembly, but reading it is how you check what the compiler did: inlining, vectorisation, bounds checks, allocation. The tools:

Language How to see the generated code
C / C++ gcc -O2 -S -masm=intel f.c; objdump -d -M intel a.out; Compiler Explorer (godbolt.org)
Rust cargo rustc --release -- --emit asm; cargo-show-asm (cargo asm crate::func); Compiler Explorer
Zig zig build-obj -O ReleaseFast -femit-asm=out.s f.zig; Compiler Explorer
Go go build -gcflags=-S (Go's own Plan 9-style assembler syntax); go tool objdump -s main.f ./bin
Java Bytecode: javap -c -p MyClass. JIT machine code: -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly (needs the hsdis plugin), or JITWatch

The same function across languages, at -O2 / release:

Rust
pub fn sum(xs: &[u32]) -> u32 { xs.iter().copied().fold(0, u32::wrapping_add) }
x86-64 asm
; Rust (x86-64, -C opt-level=3): vectorised. The core of the loop adds 8 u32s per instruction
.LBB0_5:
    vpaddd  ymm0, ymm0, ymmword ptr [rdi + 4*rcx]
    vpaddd  ymm1, ymm1, ymmword ptr [rdi + 4*rcx + 32]
    vpaddd  ymm2, ymm2, ymmword ptr [rdi + 4*rcx + 64]
    vpaddd  ymm3, ymm3, ymmword ptr [rdi + 4*rcx + 96]   ; 4 independent accumulators × 8 lanes
    add     rcx, 32
    cmp     rdx, rcx
    jne     .LBB0_5

The compiler applied everything in this chapter on its own: SIMD (ymm, 256-bit registers), four independent accumulators for ILP, and a loop with no bounds checks, because iterating a slice proves every index is in range. (The -C target-cpu=x86-64-v3 flag, or the equivalent, enables AVX2.)

Lab: seeing the hardware from software

You can't open the CPU, but you can make its behaviour visible from a C program and a timer. Every result below was measured on the sandbox this book was built on (an Intel Xeon cloud VM at 2.8 GHz, 2 vCPUs, L1d 32 KB and L2 1 MB per core, 33 MB shared L3), with GCC 13 and Clang 22. Expect different absolute numbers on your machine and the same shapes.

The memory hierarchy as a curve

Pointer chasing measures latency: an array holds one random cycle of pointers, and each load's address comes from the previous load, so the CPU can't overlap them. Varying the array size moves the working set from L1 to DRAM:

C
for (size_t i = 0; i < n; i++) buf[perm[i]] = &buf[perm[(i + 1) % n]];   // one random cycle through all slots
void **p = &buf[perm[0]];
for (size_t i = 0; i < steps; i++) p = (void **)*p;                       // each load depends on the previous one
Text
      16 KB     1.6 ns per load
      32 KB     1.6 ns per load
      64 KB     2.4 ns per load
     128 KB     3.5 ns per load
     256 KB     3.9 ns per load
     512 KB     5.2 ns per load
    1024 KB     7.7 ns per load
    2048 KB    18.4 ns per load
    4096 KB    31.5 ns per load
    8192 KB   106.6 ns per load
   16384 KB   129.3 ns per load
   32768 KB   143.8 ns per load
   65536 KB   116.7 ns per load
  262144 KB   164.2 ns per load
1 ns 10 ns 100 ns 16 KB 256 KB 4 MB 64 MB 256 MB L1 L2 L3 DRAM working-set size (log scale)
Measured load latency against working-set size, both on log scales. The plateaus are the cache levels: about 1.6 ns while the data fits in L1, rising through L2, a further step in L3, then a cliff to well over 100 ns when the random walk falls out to DRAM and misses the TLB as well. A 100× range in latency for the same instruction.

The steps are the cache levels: ~1.6 ns (about 4–5 cycles) while the working set fits in L1, a few ns in L2, tens of ns in L3, and 100–165 ns once most loads go to DRAM. The L3 plateau is shorter than its 33 MB size suggests for two reasons worth knowing at L3: the cache is shared with the other core and the hypervisor's neighbours, and a random walk over many megabytes also misses the TLB (each 4 KB page needs a translation; chapter 8), adding a page-table walk to many loads. Huge pages (2 MB) shrink that cost, which is why databases and JVMs often enable them.

The number to remember: a DRAM miss costs about 100× an L1 hit, the time for several hundred simple instructions. That's the budget an algorithm wastes on every cache miss, and why chapter 3's shuffled linked list was 144× slower than an array.

Branch prediction: sorted data runs faster

The same loop (add elements ≥ 128) over the same million random bytes, unsorted and then sorted. First compiled normally:

C
for (int i = 0; i < n; i++) { if (d[i] >= 128) s += d[i]; }
Text
[gcc -O2]  unsorted, branch: 17.1 ms   sorted, branch: 13.2 ms

Only 30% apart, because GCC was cleverer than the experiment: the assembly shows a cmovg (conditional move), so there is no branch to mispredict. Disabling if-conversion forces a real conditional jump:

Text
[gcc -O2 -fno-if-conversion]
unsorted, branch:       97.2 ms
unsorted, branchless:   13.3 ms     (int m = -(d[i] >= 128); s += d[i] & m;)
sorted,   branch:       13.3 ms

With a real branch, unsorted data is 7.3× slower. On random bytes the branch goes each way half the time, so the predictor is wrong about half the time, and each misprediction throws away the speculatively executed work in the pipeline (15–20 cycles). Sorted, the branch is "no" for the first half and "yes" for the second, so the predictor is almost always right. The branchless version computes a mask and is fast regardless of order.

L4 lessons: (1) when a loop's speed depends on the data's order rather than its size, suspect branch prediction; (2) compilers often remove branches for you (cmov, SIMD masks), so measure the actual binary and read its assembly before "optimising"; (3) perf stat -e branch-misses measures it directly on bare metal (performance counters are often unavailable in VMs and containers, as in this sandbox).

Instruction-level parallelism and SIMD

Summing 16,384 floats (64 KB, so it stays in cache and measures the core, not memory):

C
float one_chain(void) { float s = 0; for (int i = 0; i < N; i++) s += x[i]; return s; }
float four_chains(void) {
    float s0 = 0, s1 = 0, s2 = 0, s3 = 0;
    for (int i = 0; i < N; i += 4) { s0 += x[i]; s1 += x[i + 1]; s2 += x[i + 2]; s3 += x[i + 3]; }
    return (s0 + s1) + (s2 + s3);
}
Text
[gcc -O2]
one chain:   1.242 ns/element
four chains: 0.317 ns/element
[gcc -O3 -ffast-math -march=native]
one chain:   0.149 ns/element
four chains: 0.149 ns/element
  • One chain at 1.24 ns per element is about 3.5 cycles: exactly the latency of a floating-point add. Each s += x[i] must wait for the previous add to finish; the core's several FP units sit idle.
  • Four independent chains: 3.9× faster. The out-of-order core runs the four additions in parallel because they don't depend on each other. Same instruction count, different dependency graph.
  • With -O3 -ffast-math -march=native the compiler vectorises both versions with AVX (8 floats per instruction, several accumulators), reaching 0.15 ns per element, about 8× faster again. It needs -ffast-math because reordering float additions changes the rounding (chapter 6): without permission to reassociate, the compiler must keep your exact order of additions, and it can't vectorise a single chain.

This is why numerical libraries (BLAS, NumPy, PyTorch) are fast and naive loops in interpreted languages are slow: a Python loop costs tens of nanoseconds per element in interpreter overhead before the hardware even matters.

Three instruction sets, one function

The same function compiled by Clang 22 for x86-64, ARM64 and RISC-V (-O1, vectorisation off so the loop stays readable):

C
long sum_pos(const long *a, long n) {
    long s = 0;
    for (long i = 0; i < n; i++) if (a[i] > 0) s += a[i];
    return s;
}
x86-64 asm
; x86-64 (CISC: variable-length instructions, memory operands, 2-operand form)
.loop:  movq    (%rdi,%rdx,8), %r8      ; load a[i] with a scaled-index addressing mode
        testq   %r8, %r8
        cmovleq %rcx, %r8               ; branchless: replace with 0 if <= 0
        addq    %r8, %rax
        incq    %rdx
        cmpq    %rdx, %rsi
        jne     .loop
ARM64 asm
// ARM64 (RISC: fixed 4-byte instructions, load/store architecture, 3-operand form)
.loop:  ldr     x9, [x0], #8            // load and post-increment the pointer in one instruction
        subs    x1, x1, #1              // decrement counter and set flags
        bic     x9, x9, x9, asr #63     // x9 & ~(x9 >> 63): clears negative values (shifted-operand trick)
        add     x8, x9, x8
        b.ne    .loop
Text
# RISC-V (RISC: minimal base ISA; no flags register, no conditional move in the base ISA)
.loop:  ld      a3, 0(a0)
        sgtz    a4, a3                  # a4 = (a3 > 0) ? 1 : 0
        neg     a4, a4                  # 0 or all-ones mask
        and     a3, a3, a4
        addi    a0, a0, 8
        add     a2, a2, a3
        bne     a0, a1, .loop           # compare-and-branch in one instruction
Text
x86_64:  16 instructions, 42 bytes of code   (instructions 2–5 bytes each, e.g. 4c 0f 4e c1 = cmovleq)
aarch64: 13 instructions, 52 bytes of code   (every instruction exactly 4 bytes)
riscv64: 13 instructions, 34 bytes of code   (compressed 2-byte forms from the C extension)

The design philosophies show in a dozen lines. x86-64 folds address arithmetic into loads and keeps a flags register; ARM64 packs work into each fixed-size instruction (post-increment addressing, shifted operands) and makes decoding simple; RISC-V keeps the base ISA tiny and regular (no flags: comparisons write a register; branches compare two registers directly) with optional extensions like compressed instructions for density. All three compilers independently chose branchless code for this if. For a software engineer the practical differences show up in performance portability (memory ordering is weaker on ARM, which exposes concurrency bugs that x86's stronger ordering hides: Volume 17, ch. 194B), in SIMD code, and in cost (ARM server instances such as AWS Graviton are typically cheaper per unit of performance).

Revision sheet: computer architecture

Key ideas

  • Transistors make gates; gates make adders, multiplexers and registers; those make an ALU, a control unit and a register file.
  • Stored-program machines keep instructions and data in the same memory; the program counter drives the fetch–decode–execute cycle.
  • The ISA (x86-64, ARM64, RISC-V) is the contract: instructions, registers, memory model, calling conventions. Microarchitecture is how a particular chip implements it.
  • Pipelining overlaps instruction stages; hazards (data, control, structural) cause stalls. Superscalar out-of-order cores issue several independent instructions per cycle and retire them in order.
  • Branch prediction guesses outcomes; a misprediction flushes the pipeline (about 15–20 cycles). Speculative execution made attacks like Spectre possible.
  • The memory hierarchy (registers, L1, L2, L3, RAM, SSD) trades size for speed; caches exploit temporal and spatial locality, move 64-byte lines, and are kept coherent across cores (MESI-style protocols).
  • False sharing: independent variables on one cache line make cores fight over it.
  • Virtual memory hardware (MMU, page tables, TLB) translates addresses per process (chapter 8).
  • SIMD instructions (SSE/AVX, NEON) operate on several values at once; multicore gives parallelism only to programs that split their work.

Numbers to remember

Event Approximate latency
L1 hit ~1 ns (4–5 cycles)
L2 hit ~4 ns
L3 hit ~10–15 ns
Branch mispredict ~5 ns
RAM access ~80–100 ns
NVMe SSD read ~20–100 µs
Same-region network round trip ~0.5 ms
  • Cache line: 64 bytes on x86 and most ARM (Apple M-series chips report 128 bytes). Page: 4 KB by default (16 KB on Apple silicon).

Pitfalls

  • Traversing memory against its layout (column order in row-major arrays): about 10× slower in this chapter's measurement.
  • Linked structures scattered across the heap defeat prefetching.
  • Unpredictable branches in hot loops; consider branchless code or sorted data.
  • Two threads updating counters in the same cache line (false sharing).
  • Benchmarking without warming caches or repeating runs.

Glossary

  • Clock cycle: one tick; at 3 GHz about 0.33 ns.
  • IPC: instructions per cycle.
  • Register: a tiny, fastest storage slot in the CPU.
  • Cache miss: the requested line isn't in that cache level.
  • TLB: a cache of address translations.
  • RISC / CISC: reduced (simple, fixed-length) vs complex instruction sets.