Lesson 2 of 7

The CPU: Fetch, Decode, Execute

A CPU repeats one billions of times per second: fetch the next instruction, decode it, execute it. You'll see what instructions look like and how modern CPUs speed this loop up.

Machine instructions are tiny: load this address into a register, add two registers, compare, jump somewhere else if the result was zero. Registers are a few dozen very fast storage slots (64 each on modern machines) where all actual work happens. The program counter register holds the address of the next instruction; jumps just overwrite it.

x86-64 assembly
; What 'x = a + b' compiles to (x86-64 assembly):
mov  rax, [a]      ; fetch a from memory into register rax
add  rax, [b]      ; add b's value to it
mov  [x], rax      ; store the result back to memory

; What 'if (x == 0) goto done' looks like:
cmp  rax, 0        ; compare, sets CPU flags
je   done          ; 'jump if equal' — reads the flags

; A loop is a compare and a backwards jump:
loop_start:
  dec  rcx         ; count down
  jnz  loop_start  ; jump if not zero

Clock speed (say 3 GHz — 3 billion cycles per second) the rhythm, but modern CPUs don't do one instruction per cycle. They (overlap the fetch/decode/execute stages of many instructions like an line), execute out of order when instructions don't depend on each other, and are superscalar (multiple instructions per cycle). A modern core juggles hundreds of instructions in flight.

Bash
# See it yourself — compile and disassemble:
cat > tiny.c << 'EOF'
int add(int a, int b) { return a + b; }
EOF
gcc -O1 -c tiny.c && objdump -d tiny.o

# Output includes:
#   lea eax, [rdi+rsi]     <- the entire function: one instruction
# (or paste the C into https://godbolt.org)
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.