Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Instruction cycle -- Fetch, Decode, Execute, Write Back

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:

  1. Fetch (take the order): pick up a new order ticket from the front desk and see what the customer ordered
  2. 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
  3. Execute (cook the dish): actually turn on the stove and cook--chopping, stir-frying, seasoning
  4. 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:

  1. The CPU puts the address from the PC onto the address bus
  2. The CPU issues a "read" signal on the control bus
  3. Memory returns the instruction data at that address
  4. The instruction is placed into the Instruction Register (IR)
  5. 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:

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:

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

       

print

(

f

"[System] Program loaded, {len(instructions)} instructions in total"

)

       

print

(

f

"[System] Initial registers: {self.registers}"

)

       

print

(

"="

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

       

print

(

f

"[Cycle {self.total_cycles}] Fetch (IF)"

)

       

print

(

f

" PC={old_pc} -> read instruction from memory address {old_pc}"

)

       

print

(

f

" Instruction content: "{instruction}""

)

       

print

(

f

" PC update: {old_pc} -> {self.pc}"

)

       

print

(

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

       

print

(

f

"[Cycle {self.total_cycles}] Decode (ID)"

)

       

print

(

f

" Opcode: {opcode}"

)

       

print

(

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:

           

print

(

f

" Meaning: {opcode_meaning[opcode]}"

)

       

return

opcode

,

operands

   

def

execute

(

self

,

opcode

,

operands

)

:

       

"""Stage 3: Execute"""

       

self

.

total_cycles

=

1

       

self

.

stats

[

'execute'

]

=

1

       

print

(

f

"[Cycle {self.total_cycles}] Execute (EX)"

)

       

if

opcode

==

'HALT'

:

           

print

(

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

]

)

           

print

(

f

" Operation: load immediate {value} into register {reg}"

)

           

print

(

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

           

print

(

f

" Operation: ALU computes {rx}({a}) + {ry}({b}) = {result}"

)

           

print

(

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

           

print

(

f

" Operation: ALU computes {rx}({a}) * {ry}({b}) = {result}"

)

           

print

(

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

)

           

print

(

f

" Operation: compare {rx}({a}) and {ry}({b})"

)

           

print

(

f

" Result: ZERO={self.flags['ZERO']}, GREATER={self.flags['GREATER']}"

)

           

print

(

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

               

print

(

f

" Condition met (GREATER=True): PC jumps {old_pc} -> {target}"

)

               

print

(

f

" Components involved: controller, PC register"

)

           

else

:

               

print

(

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

]

           

print

(

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

:

           

print

(

f

"[Cycle {self.total_cycles}] Write Back (WB) - no operation"

)

           

return

        action_type

=

action

[

0

]

       

print

(

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

           

print

(

f

" Target: register {reg}"

)

           

print

(

f

" Data: {old_val} -> {value}"

)

           

print

(

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

           

print

(

f

" Target: register {reg}"

)

           

print

(

f

" Data: {old_val} -> {result}"

)

           

print

(

f

" Path: ALU output -> register file (internal bus)"

)

       

elif

action_type

==

'OUTPUT'

:

            reg

,

value

=

action

[

1

]

,

action

[

2

]

           

print

(

f

" Output: register {reg} = {value}"

)

           

print

(

f

" Path: register file -> data bus -> I/O interface"

)

       

print

(

f

" Current register state: {self.registers}"

)

       

print

(

f

" Flags: {self.flags}"

)

       

print

(

"-"

60

)

   

def

run

(

self

)

:

       

"""Run the whole program, executing instruction by instruction"""

       

print

(

"="

60

)

       

print

(

"SimpleCPU simulator starting -- instruction cycle demo (runoob)"

)

       

print

(

"="

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

       

print

(

"\n"

"="

60

)

       

print

(

"Program execution finished! Statistics:"

)

       

print

(

f

" Total clock cycles: {self.total_cycles}"

)

       

print

(

f

" Fetch stage executions: {self.stats['fetch']} times"

)

       

print

(

f

" Decode stage executions: {self.stats['decode']} times"

)

       

print

(

f

" Execute stage executions: {self.stats['execute']} times"

)

       

print

(

f

" Write Back stage executions: {self.stats['writeback']} times"

)

       

print

(

f

" Final registers: {self.registers}"

)

       

print

(

f

" Final flags: {self.flags}"

)

       

print

(

f

" Final PC: {self.pc}"

)

       

print

(

"="

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:

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.