Instruction cycle -- Fetch, Decode, Execute, Write Back
Every instruction the CPU executes follows the same four-step process, like the beat of a never-stopping assembly line. This lesson takes you deep into what each of the four steps does and uses Python to simulate the instruction execution of a complete CPU.
An analogy from daily life: a restaurant kitchen
Imagine you are the head chef of a restaurant. After a customer places an order, you prepare the dish following these steps:
- Fetch (take the order): pick up a new order ticket from the front desk and see what the customer ordered
- Decode (read the order): analyze the ticket--"braised pork" needs pork belly, soy sauce and rock sugar, "stir-fried vegetables" needs greens and minced garlic
- Execute (cook the dish): actually turn on the stove and cook--chopping, stir-frying, seasoning
- Write Back (plate the dish): put the finished dish on a plate and hand it to the waiter to serve
Every order ticket goes through these four steps. After finishing one dish, you take the next ticket. The CPU works the same way--fetch an instruction, decode an instruction, execute an instruction, write back the result, over and over.
This four-step cycle is the most fundamental working rhythm of the CPU. Every second from the moment your computer boots up to the moment it shuts down, the CPU keeps repeating the "fetch-decode-execute-write back" cycle, billions of times per second.
Detailed explanation of the four stages
Stage one: Fetch
First, the CPU must "fetch" the next instruction to execute from memory.
There is a special register called the Program Counter (PC), which always holds the address in memory of the next instruction.
What the fetch stage does:
- The CPU puts the address from the PC onto the address bus
- The CPU issues a "read" signal on the control bus
- Memory returns the instruction data at that address
- The instruction is placed into the Instruction Register (IR)
- The PC automatically increments by 1, pointing to the next instruction
There is a key design here: the PC auto-increments. This means the CPU by default executes instructions in order, unless a jump instruction (such as if-else or a loop) changes the value of the PC.
Stage two: Decode
The fetched instruction is a string of binary digits (for example 0001 0010 0011), and the CPU needs to "translate" it.
Core work of the decode stage:
- Identify the Opcode: the first few bits of the instruction tell the CPU what to do--addition, subtraction, loading data, or a jump?
- Extract the Operands: the following bits of the instruction specify the operation targets--which register? which address in memory?
- Set control signals: based on the decode result, the controller sends corresponding control signals to the ALU, register file, buses and other components
For example, an instruction ADD R1, R2, R3, after decoding the CPU knows: let the ALU perform addition, with inputs from registers R2 and R3, and store the result into R1.
Stage three: Execute
This is the stage where the instruction really "does the work". Depending on the instruction type, what the execute stage does also differs:
| Instruction type | What the execute stage does | Hardware involved |
|---|---|---|
| Arithmetic operations (ADD, SUB, etc.) | The ALU operates on the operands | ALU, register file |
| Logical operations (AND, OR, etc.) | The ALU performs bitwise operations on the operands | ALU, register file |
| Memory read (LOAD) | Access memory via the address bus and read data | Address bus, data bus, memory |
| Memory write (STORE) | Access memory via the address bus and write data | Address bus, data bus, memory |
| Jump (JUMP, BRANCH) | Modify the value of the PC to change the execution flow | Controller, PC register |
Stage four: Write Back
The result produced by the execute stage needs to be "written" to the target location.
Possible write-back targets:
- Register: store the operation result into a general-purpose register (most common)
- Memory: store the result into some address in memory
- Flag register: update status flags (such as whether the result is zero, overflows, is negative, etc.)
After write-back completes, the execution cycle of one instruction formally ends. If the PC still points to a valid instruction address, the CPU automatically returns to the fetch stage and starts the next instruction.
Timeline view of the instruction cycle
The timeline below shows the complete process of 3 instructions executing one after another:
时钟周期: 1 2 3 4 5 6 7 8 9 10 11 12
指令1: [取指] [译码] [执行] [写回]
指令2: [取指] [译码] [执行] [写回]
指令3: [取指] [译码] [执行] [写回]
↑ 指令1 完成后才开始指令2,完全串行执行
Note that here each instruction takes 4 cycles, so 3 instructions take 12 cycles in total. When we get to pipelining later, you will see how to greatly shorten this time.
Interactive demo: SimpleCPU simulator
The Python program below simulates the complete instruction cycle of a minimal CPU. It supports LOAD (load value), ADD (addition), MUL (multiplication), CMP (compare + conditional jump) and STORE (print output) instructions, and prints detailed logs for each stage.
Example
"""
SimpleCPU simulator -- complete instruction cycle demo
Supported instructions: LOAD, ADD, MUL, CMP+JGT, STORE, HALT
Every instruction goes through: Fetch (IF) -> Decode (ID) -> Execute (EX) -> Write Back (WB)
"""
class
SimpleCPU:
"""A CPU simulator for teaching, demonstrating the four stages of the instruction cycle"""
def
init
(
self
)
:
General-purpose registers: R0~R3, all initialized to 0
self
.
registers
=
{
'R0'
:
0
,
'R1'
:
0
,
'R2'
:
0
,
'R3'
:
0
}
Flag register: records comparison results
self
.
flags
=
{
'ZERO'
:
False
,
'GREATER'
:
False
}
Program counter: points to the location of the next instruction in memory
self
.
pc
=
0
Instruction register: holds the instruction currently being executed
self
.
ir
=
None
Memory: holds the instruction sequence of the program
self
.
memory
=
[
]
Count the number of executions of each stage
self
.
stats
=
{
'fetch'
:
0
,
'decode'
:
0
,
'execute'
:
0
,
'writeback'
:
0
}
self
.
total_cycles
=
0
Control flags
self
.
running
=
False
def
load_program
(
self
,
instructions
)
:
"""Load the instruction list into memory"""
self
.
memory
=
instructions
self
.
pc
=
0
self
.
running
=
True
(
f
"[System] Program loaded, {len(instructions)} instructions in total"
)
(
f
"[System] Initial registers: {self.registers}"
)
(
"="
60
)
def
fetch
(
self
)
:
"""Stage 1: Fetch (Instruction Fetch)"""
self
.
total_cycles
=
1
if
self
.
pc
=
len
(
self
.
memory
)
:
self
.
running
=
False
return
None
Read the instruction pointed to by the PC from memory
instruction
=
self
.
memory
[
self
.
pc
]
self
.
ir
=
instruction
old_pc
=
self
.
pc
self
.
pc
=
1
The PC auto-increments
self
.
stats
[
'fetch'
]
=
1
(
f
"[Cycle {self.total_cycles}] Fetch (IF)"
)
(
f
" PC={old_pc} -> read instruction from memory address {old_pc}"
)
(
f
" Instruction content: "{instruction}""
)
(
f
" PC update: {old_pc} -> {self.pc}"
)
(
f
" IR ← "{instruction}""
)
return
instruction
def
decode
(
self
,
instruction
)
:
"""Stage 2: Decode (Instruction Decode)"""
self
.
total_cycles
=
1
self
.
stats
[
'decode'
]
=
1
Parse the opcode and operands
parts
=
instruction.
split
(
)
opcode
=
parts
[
0
]
.
upper
(
)
Opcode
operands
=
parts
[
1
:
]
if
len
(
parts
)
1
else
[
]
operands
(
f
"[Cycle {self.total_cycles}] Decode (ID)"
)
(
f
" Opcode: {opcode}"
)
(
f
" Operands: {operands}"
)
Explain the meaning of the opcode
opcode_meaning
=
{
'LOAD'
:
'Load immediate into register'
,
'ADD'
:
'Register addition'
,
'MUL'
:
'Register multiplication'
,
'CMP'
:
'Compare the values of two registers'
,
'JGT'
:
'Conditional jump (jump if greater)'
,
'STORE'
:
'Output the register value'
,
'HALT'
:
'Stop execution'
,
}
if
opcode
in
opcode_meaning:
(
f
" Meaning: {opcode_meaning[opcode]}"
)
return
opcode
,
operands
def
execute
(
self
,
opcode
,
operands
)
:
"""Stage 3: Execute"""
self
.
total_cycles
=
1
self
.
stats
[
'execute'
]
=
1
(
f
"[Cycle {self.total_cycles}] Execute (EX)"
)
if
opcode
==
'HALT'
:
(
f
" HALT: end program execution"
)
self
.
running
=
False
elif
opcode
==
'LOAD'
:
LOAD Rx, value -> store immediate value into register Rx
reg
=
operands
[
0
]
value
=
int
(
operands
[
1
]
)
(
f
" Operation: load immediate {value} into register {reg}"
)
(
f
" Components involved: data bus (transfers immediate {value})"
)
Temporarily store the result; the register is updated in the write-back stage
return
(
'LOAD'
,
reg
,
value
)
elif
opcode
==
'ADD'
:
ADD Rx, Ry → Rx = Rx + Ry
rx
,
ry
=
operands
[
0
]
,
operands
[
1
]
a
=
self
.
registers
[
rx
]
b
=
self
.
registers
[
ry
]
result
=
a + b
(
f
" Operation: ALU computes {rx}({a}) + {ry}({b}) = {result}"
)
(
f
" Components involved: ALU (arithmetic unit), register file"
)
return
(
'WRITE_REG'
,
rx
,
result
)
elif
opcode
==
'MUL'
:
MUL Rx, Ry → Rx = Rx * Ry
rx
,
ry
=
operands
[
0
]
,
operands
[
1
]
a
=
self
.
registers
[
rx
]
b
=
self
.
registers
[
ry
]
result
=
a * b
(
f
" Operation: ALU computes {rx}({a}) * {ry}({b}) = {result}"
)
(
f
" Components involved: ALU (arithmetic unit), register file"
)
return
(
'WRITE_REG'
,
rx
,
result
)
elif
opcode
==
'CMP'
:
CMP Rx, Ry -> compare two registers and set the flag bits
rx
,
ry
=
operands
[
0
]
,
operands
[
1
]
a
=
self
.
registers
[
rx
]
b
=
self
.
registers
[
ry
]
self
.
flags
[
'ZERO'
]
=
(
a
==
b
)
self
.
flags
[
'GREATER'
]
=
(
a
b
)
(
f
" Operation: compare {rx}({a}) and {ry}({b})"
)
(
f
" Result: ZERO={self.flags['ZERO']}, GREATER={self.flags['GREATER']}"
)
(
f
" Components involved: ALU (comparator), flag register"
)
return
(
'FLAGS'
,
None
,
None
)
elif
opcode
==
'JGT'
:
JGT address -> if the GREATER flag is true, jump to address
target
=
int
(
operands
[
0
]
)
if
self
.
flags
[
'GREATER'
]
:
old_pc
=
self
.
pc
self
.
pc
=
target
(
f
" Condition met (GREATER=True): PC jumps {old_pc} -> {target}"
)
(
f
" Components involved: controller, PC register"
)
else
:
(
f
" Condition not met (GREATER=False): no jump, PC stays at {self.pc}"
)
return
None
elif
opcode
==
'STORE'
:
STORE Rx -> output the value of the register
reg
=
operands
[
0
]
value
=
self
.
registers
[
reg
]
(
f
" Operation: output the value of register {reg}"
)
return
(
'OUTPUT'
,
reg
,
value
)
return
None
def
writeback
(
self
,
action
)
:
"""Stage 4: Write Back"""
self
.
total_cycles
=
1
self
.
stats
[
'writeback'
]
=
1
if
action
is
None
:
(
f
"[Cycle {self.total_cycles}] Write Back (WB) - no operation"
)
return
action_type
=
action
[
0
]
(
f
"[Cycle {self.total_cycles}] Write Back (WB)"
)
if
action_type
==
'LOAD'
:
reg
,
value
=
action
[
1
]
,
action
[
2
]
old_val
=
self
.
registers
[
reg
]
self
.
registers
[
reg
]
=
value
(
f
" Target: register {reg}"
)
(
f
" Data: {old_val} -> {value}"
)
(
f
" Path: data bus -> register file"
)
elif
action_type
==
'WRITE_REG'
:
reg
,
result
=
action
[
1
]
,
action
[
2
]
old_val
=
self
.
registers
[
reg
]
self
.
registers
[
reg
]
=
result
(
f
" Target: register {reg}"
)
(
f
" Data: {old_val} -> {result}"
)
(
f
" Path: ALU output -> register file (internal bus)"
)
elif
action_type
==
'OUTPUT'
:
reg
,
value
=
action
[
1
]
,
action
[
2
]
(
f
" Output: register {reg} = {value}"
)
(
f
" Path: register file -> data bus -> I/O interface"
)
(
f
" Current register state: {self.registers}"
)
(
f
" Flags: {self.flags}"
)
(
"-"
60
)
def
run
(
self
)
:
"""Run the whole program, executing instruction by instruction"""
(
"="
60
)
(
"SimpleCPU simulator starting -- instruction cycle demo (runoob)"
)
(
"="
60
)
while
self
.
running
:
The loop of the four stages
instruction
=
self
.
fetch
(
)
Stage 1: Fetch
if
instruction
is
None
:
break
opcode
,
operands
=
self
.
decode
(
instruction
)
Stage 2: Decode
action
=
self
.
execute
(
opcode
,
operands
)
Stage 3: Execute
self
.
writeback
(
action
)
Stage 4: Write Back
After execution finishes, print the statistics
(
"\n"
"="
60
)
(
"Program execution finished! Statistics:"
)
(
f
" Total clock cycles: {self.total_cycles}"
)
(
f
" Fetch stage executions: {self.stats['fetch']} times"
)
(
f
" Decode stage executions: {self.stats['decode']} times"
)
(
f
" Execute stage executions: {self.stats['execute']} times"
)
(
f
" Write Back stage executions: {self.stats['writeback']} times"
)
(
f
" Final registers: {self.registers}"
)
(
f
" Final flags: {self.flags}"
)
(
f
" Final PC: {self.pc}"
)
(
"="
60
)
===== Run the demo program =====
Program logic: compute the result of 1+2, then multiply by 3, and compare with 10
LOAD R0, 1 → R0 = 1
LOAD R1, 2 → R1 = 2
ADD R0, R1 → R0 = R0 + R1 = 1 + 2 = 3
LOAD R2, 3 → R2 = 3
MUL R0, R2 → R0 = R0 * R2 = 3 * 3 = 9
CMP R0, R2 -> compare R0(9) and R2(3), set GREATER=True
STORE R0 -> output the value of R0
HALT -> stop
cpu
=
SimpleCPU
(
)
program
=
[
"LOAD R0 1"
,
R0 = 1
"LOAD R1 2"
,
R1 = 2
"ADD R0 R1"
,
R0 = R0 + R1 = 3
"LOAD R2 3"
,
R2 = 3
"MUL R0 R2"
,
R0 = R0 * R2 = 9
"CMP R0 R2"
,
Compare 9 and 3, GREATER=True
"JGT 8"
,
If GREATER, jump to instruction 8
"LOAD R3 0"
,
(This one will not execute, because JGT skipped it)
"STORE R0"
,
Output R0 = 9
"HALT"
,
Stop
]
cpu.
load_program
(
program
)
cpu.
run
(
)
The code above prints detailed logs for every stage of every instruction, so you can clearly see what the CPU does internally on each clock cycle. Pay attention to:
- PC auto-increment: for each instruction executed, the PC automatically increments by 1 (fetch stage)
- Conditional jump: the CMP+JGT combination implements an if check--if R0 > R2, jump to instruction 8, skipping instruction 7
- Registers as a transfer station: all data must first be loaded into registers; the ALU reads operands from registers, computes, and writes results back to registers
Interactive demo: CPU internal structure & instruction cycle step-by-step playback
Below, a simplified diagram of the CPU internal structure is drawn with vis-network. Click the "Next Step" button to observe which hardware components the instruction uses in each of the four stages; activated components are highlighted in the color of the corresponding stage.
CPU internal structure & instruction cycle step-by-step demo (runoob)
Fetch IF
Decode ID
Execute EX
Write Back WB
Click "Next Step" to start the instruction cycle demo and observe which components inside the CPU are activated in each stage.