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

The complete journey of an instruction

The complete journey of an instruction

From the binary foundations in the first lesson to the I/O system in the previous lesson--we have learned all the core content of computer organization. This lesson strings these knowledge points together into one thread, tracing the complete journey of an instruction from birth to completion.

We will implement a complete von Neumann computer simulator (FullComputer), which includes: a four-layer storage structure (disk, memory, cache, registers), DMA data transfer, a four-stage fetch-decode-execute-write back pipeline, bus interaction, and cache hit rate statistics. Finally it prints a complete execution report.


Review: knowledge map of the six modules

Before starting the end-to-end simulation, let us quickly review the core concepts of each of the six modules of this course:

module Topic Core Concepts How it appears in this lesson
Module one Binary and information representation 0/1 encoding, base conversion, two's complement, floating-point numbers Instructions and data are both stored in binary form in memory
Module two Logic gates and digital circuits AND/OR/NOT gates, adders, ALU The ALU operations in the execute stage are implemented by gate circuits
Module three von Neumann architecture Five major components, stored program, instruction cycle What this lesson simulates is exactly a complete von Neumann machine
Module four CPU principles Registers, PC, IR, pipeline, four stages All four stages fetch-decode-execute-write back are simulated
Module five Storage system Memory hierarchy, cache, principle of locality Disk -> memory -> cache -> register, the full chain of four storage levels
Module six Bus and I/O Address/data/control buses, polling/interrupt/DMA DMA loads the program, the bus transfers data, cache lines are filled

The complete lifecycle of an instruction

We take a simple pseudo-instruction ADD A, B(add the values of registers A and B, store the result back into A) as an example and trace its complete journey:

Journey step one: the program is stored on the disk

The program is initially stored on the disk as a file. The disk is persistent storage: data is not lost after power-off, but read/write speed is the slowest (millisecond level).

Journey step two: DMA loads the program into memory

When you double-click to run the program, the operating system uses DMA to move the program from the disk to memory. The DMA controller takes over the data transfer, and the CPU can do other things during this time.

Journey step three: the CPU fetches the instruction via the bus

The CPU puts the value of the Program Counter (PC) onto the address bus and issues a "read" signal on the control bus. After memory receives the signal, it places the instruction at the corresponding address onto the data bus, and the CPU reads it into the Instruction Register (IR).

Journey step four: decode--the controller parses the instruction

ADD A, B in the instruction register is broken into three parts: opcode ADD, destination operand A, source operand B. The controller decides the next operation based on the opcode.

Journey step five: execute--the ALU performs the operation

The controller sends control signals, having the ALU fetch values from registers A and B, perform the addition, and temporarily hold the result at the ALU output.

Journey step six: write back--the result is stored into the register via the data bus

The ALU computation result is written back into register A via the data bus. At this point, one instruction has finished executing. The PC automatically increments by 1, pointing to the next instruction.


Code demo: FullComputer complete simulation

The FullComputer class below fully simulates the entire process described above. It contains over 300 lines of code, covering the knowledge points of all six modules of this course. Every step prints detailed logs.

Example

"""
FullComputer - complete von Neumann computer simulator (runoob teaching demo)

This program implements a complete (simplified) von Neumann computer, including:

Supported instruction set:
  LOAD reg value - load immediate into register
  STORE reg addr - store register value into memory address
  ADD dst src      - dst = dst + src
  SUB dst src      - dst = dst - src
  MUL dst src      - dst = dst * src
  CMP a b - compare two registers and set flag bits
  JMP addr - unconditional jump
  JZ addr - jump if the zero flag is true

How to run: python fullcomputer.py
"""

import

time

============================

1. Storage system - four-layer structure

============================

class

Disk:

   

"""
    Disk - the lowest-level persistent storage.
    Slowest speed (millisecond level), largest capacity, data not lost on power-off.
    """

   

def

init

(

self

)

:

       

self

.

sectors

=

{

}

         

Sector storage, simulating disk sectors

       

self

.

read_latency

=

5

     

Read latency (simulated time units)

       

self

.

write_latency

=

8

   

Write latency

   

def

load_program

(

self

,

program_name

)

:

       

"""Load the program stored on the disk. Returns None if the program does not exist."""

       

if

program_name

in

self

.

sectors

:

           

print

(

f

" [Disk] Found program '{program_name}', size: {len(self.sectors[program_name])} instructions"

)

           

return

self

.

sectors

[

program_name

]

       

print

(

f

" [Disk] Program '{program_name}' not found!"

)

       

return

None

   

def

store_program

(

self

,

name

,

program

)

:

       

"""Store the program onto the disk"""

       

self

.

sectors

[

name

]

=

program

       

print

(

f

" [Disk] Stored program '{name}' ({len(program)} instructions) to sector 0x{hash(name) & 0xFFFF:04X}"

)

class

Memory:

   

"""
    Main memory - the second storage layer.
    Medium speed (nanosecond level), fairly large capacity, data lost on power-off.
    The CPU can only directly access data in memory (it cannot directly access the disk).
    """

   

def

init

(

self

,

size

=

65536

)

:

       

self

.

size

=

size          

Memory size (bytes)

       

self

.

cells

=

{

}

           

Memory cells, keyed by address, with data/instruction as value

       

self

.

read_count

=

0

       

Read operation count

       

self

.

write_count

=

0

     

Write operation count

   

def

read

(

self

,

addr

)

:

       

"""Read data from a specified address"""

       

self

.

read_count

=

1

       

if

addr

not

in

self

.

cells

:

           

print

(

f

" Warning: address {addr} not initialized, returning 0"

)

           

return

0

       

return

self

.

cells

[

addr

]

   

def

write

(

self

,

addr

,

data

)

:

       

"""Write data to a specified address"""

       

self

.

write_count

=

1

       

self

.

cells

[

addr

]

=

data

   

def

load_block

(

self

,

start_addr

,

data_block

)

:

       

"""
        Load a whole block of data into a contiguous address region of memory.
        Used for DMA bulk transfer scenarios.
        """

       

for

i

,

item

in

enumerate

(

data_block

)

:

           

self

.

cells

[

start_addr + i

]

=

item

       

return

len

(

data_block

)

class

Cache:

   

"""
    Cache (L1 Cache simulation) - the third storage layer.
    Extremely fast (same frequency as the CPU), smallest capacity.

    Uses a simple direct-mapped cache model:
    - Each cache line stores: (memory address, data content)
    - Cache hit: data is already in the cache, return directly
    - Cache miss: need to load from memory, replacing a cache line
    """

   

def

init

(

self

,

num_lines

=

8

)

:

       

self

.

num_lines

=

num_lines

       

self

.

lines

=

{

}

           

Cache line: {cache_line_index: (mem_addr, data)}

       

self

.

hit_count

=

0

       

self

.

miss_count

=

0

   

def

read

(

self

,

mem_addr

,

memory

)

:

       

"""
        Read from the cache. If hit, return directly; if miss, load from memory.
        Returns: (data, was_hit)
        """

       

Simple mapping: cache line index = memory address % number of cache lines

        line_index

=

mem_addr %

self

.

num_lines

       

if

line_index

in

self

.

lines

:

            cached_addr

,

cached_data

=

self

.

lines

[

line_index

]

           

if

cached_addr

==

mem_addr:

               

Cache hit

               

self

.

hit_count

=

1

               

print

(

f

" [Cache] Hit! Line {line_index}, address {mem_addr}, data: {cached_data}"

)

               

return

cached_data

,

True

       

Cache miss

       

self

.

miss_count

=

1

        data

=

memory.

read

(

mem_addr

)

       

self

.

lines

[

line_index

]

=

(

mem_addr

,

data

)

       

print

(

f

" [Cache] Miss, loading data {data} from memory address {mem_addr} -> cache line {line_index}"

)

       

return

data

,

False

   

@

property

   

def

hit_rate

(

self

)

:

        total

=

self

.

hit_count

self

.

miss_count

       

return

self

.

hit_count

/ total *

100

if

total

0

else

0.0

class

RegisterFile:

   

"""
    Register file - the top-level storage.
    Fastest (one clock cycle), smallest capacity.
    General-purpose registers + special registers (PC, IR, MAR, MDR, FLAGS)
    """

   

def

init

(

self

)

:

       

General-purpose registers

       

self

.

gpr

=

{

'A'

:

0

,

'B'

:

0

,

'C'

:

0

,

'D'

:

0

}

       

Special registers

       

self

.

PC

=

0

               

Program counter: holds the address of the next instruction

       

self

.

IR

=

None

           

Instruction register: holds the instruction currently being executed

       

self

.

MAR

=

0

             

Memory address register: holds the memory address to access

       

self

.

MDR

=

0

             

Memory data register: holds data read from / to be written to memory

       

Flag register

       

self

.

FLAGS

=

{

'Z'

:

False

}

 

Zero flag: whether the result of the last operation was 0

   

def

repr

(

self

)

:

        gpr_str

=

', '

.

join

(

f

'{k}={v}'

for

k

,

v

in

self

.

gpr

.

items

(

)

)

       

return

f

"GPR[{gpr_str}] PC={self.PC} IR={self.IR} FLAGS={self.FLAGS}"

============================

2. Bus system - three buses

============================

class

SystemBus:

   

"""
    System bus - includes address bus, data bus, control bus.
    Provides a unified interface for the CPU, memory and DMA.
    """

   

def

init

(

self

)

:

       

self

.

address_bus

=

0

     

Address bus: the address currently being transferred

       

self

.

data_bus

=

0

         

Data bus: the data currently being transferred

       

self

.

control_bus

=

'IDLE'

 

Control bus: IDLE, READ, WRITE, INTERRUPT, DMA_REQ, DMA_ACK

       

self

.

transfer_count

=

0

   

Bus transfer count

   

def

cpu_read

(

self

,

address

,

memory

,

cache

)

:

       

"""
        The CPU reads data from memory via the bus (through the cache).
        The complete bus interaction process:
        1. The CPU puts the address onto the address bus
        2. The CPU issues a READ signal on the control bus
        3. Memory (through the cache layer) returns data to the data bus
        4. The CPU reads data from the data bus
        5. The bus is cleared
        """

       

self

.

address_bus

=

address

       

self

.

control_bus

=

'READ'

       

self

.

transfer_count

=

1

       

print

(

f

" [Bus] Address bus <- {address}, control bus <- READ"

)

       

Memory responds through the cache layer

        data

,

was_hit

=

cache.

read

(

address

,

memory

)

       

self

.

data_bus

=

data

       

print

(

f

" [Bus] Data bus <- {data} {'(cache hit)' if was_hit else '(from memory)'}"

)

       

The CPU reads the data

        result

=

self

.

data_bus

       

The bus is cleared

       

self

.

address_bus

=

0

       

self

.

data_bus

=

0

       

self

.

control_bus

=

'IDLE'

       

print

(

f

" [Bus] Bus cleared, entering idle state"

)

       

return

result

   

def

cpu_write

(

self

,

address

,

data

,

memory

)

:

       

"""
        The CPU writes data to memory via the bus.
        """

       

self

.

address_bus

=

address

       

self

.

data_bus

=

data

       

self

.

control_bus

=

'WRITE'

       

self

.

transfer_count

=

1

       

print

(

f

" [Bus] Address bus <- {address}, data bus <- {data}, control bus <- WRITE"

)

        memory.

write

(

address

,

data

)

       

print

(

f

" [Bus] Data {data} has been written to memory address {address}"

)

       

The bus is cleared

       

self

.

address_bus

=

0

       

self

.

data_bus

=

0

       

self

.

control_bus

=

'IDLE'

       

print

(

f

" [Bus] Bus cleared, entering idle state"

)

============================

3. DMA controller

============================

class

DMAController:

   

"""
    DMA controller - responsible for transferring data directly between disk and memory.
    The CPU only needs to tell the DMA: source address, destination address, transfer length.
    After the DMA finishes the transfer, it notifies the CPU via an interrupt.
    """

   

def

init

(

self

,

bus

)

:

       

self

.

bus

=

bus

       

self

.

transfer_count

=

0

   

DMA transfer count

       

self

.

total_bytes

=

0

     

Total transferred bytes

   

def

transfer_program

(

self

,

disk

,

program_name

,

memory

,

load_addr

=

0

)

:

       

"""
        Load the program from disk to memory via DMA.
        This is a practical application of "DMA mode" from Lesson 20 of this course.
        """

       

print

(

f

"\n  {'='*50}"

)

       

print

(

f

" DMA transfer starting: disk -> memory"

)

       

print

(

f

"  {'='*50}"

)

       

print

(

f

" [DMA] Source: disk sector (program '{program_name}')"

)

       

print

(

f

" [DMA] Destination: starting at memory address 0x{load_addr:04X}"

)

       

print

(

f

" [DMA] Requesting bus control..."

)

       

DMA occupies the bus

       

self

.

bus

.

control_bus

=

'DMA_REQ'

       

print

(

f

" [DMA] Got bus control (control bus <- DMA_REQ)"

)

        program

=

disk.

load_program

(

program_name

)

       

if

program

is

None

:

           

print

(

f

" [DMA] Error: program does not exist, transfer aborted"

)

           

self

.

bus

.

control_bus

=

'IDLE'

           

return

0

       

Transfer instruction by instruction

       

for

i

,

instruction

in

enumerate

(

program

)

:

            addr

=

load_addr + i

            memory.

write

(

addr

,

instruction

)

           

self

.

bus

.

address_bus

=

addr

           

self

.

bus

.

data_bus

=

instruction

           

self

.

total_bytes

=

1

           

self

.

transfer_count

=

1

           

print

(

f

" [DMA] Transfer #{i}: instruction '{instruction}' -> memory address {addr} (0x{addr:04X})"

)

       

DMA releases the bus and sends a completion interrupt

       

self

.

bus

.

control_bus

=

'DMA_ACK'

       

print

(

f

" [DMA] Transfer complete! {len(program)} instructions in total, {self.total_bytes} bus transfers"

)

       

print

(

f

" [DMA] Released bus control (control bus <- IDLE)"

)

       

Interrupt notifies the CPU

       

print

(

f

" [DMA] Sending interrupt signal to notify CPU: program loaded"

)

       

self

.

bus

.

control_bus

=

'INTERRUPT'

       

Handling after the CPU receives the interrupt

       

time

.

sleep

(

0.001

)

       

print

(

f

" [CPU interrupt response] DMA completion interrupt received, program is ready"

)

       

self

.

bus

.

control_bus

=

'IDLE'

       

return

len

(

program

)

   

def

cache_prefetch

(

self

,

memory

,

cache

,

start_addr

,

count

)

:

       

"""
        DMA prefetch: load data that will soon be used from memory into the cache ahead of time.
        Simulates the hardware prefetch mechanism of modern CPUs.
        """

       

print

(

f

"\n [DMA Prefetch] Preloading memory addresses {start_addr}~{start_addr+count-1} into cache..."

)

       

for

i

in

range

(

count

)

:

            addr

=

start_addr + i

            data

=

memory.

read

(

addr

)

            line_index

=

addr % cache.

num_lines

            cache.

lines

[

line_index

]

=

(

addr

,

data

)

       

print

(

f

" [DMA Prefetch] Done, {count} instructions written to cache"

)

============================

4. ALU - arithmetic logic unit

============================

class

ALU:

   

"""
    Arithmetic logic unit - performs all arithmetic and logical operations.
    Corresponds to adders, logic gates and other content from Module two of the course.
    """

   

@

staticmethod

   

def

add

(

a

,

b

)

:

       

print

(

f

" [ALU] Addition: {a} + {b} = {a + b}"

)

       

return

a + b

   

@

staticmethod

   

def

sub

(

a

,

b

)

:

       

print

(

f

" [ALU] Subtraction: {a} - {b} = {a - b}"

)

       

return

a - b

   

@

staticmethod

   

def

mul

(

a

,

b

)

:

       

print

(

f

" [ALU] Multiplication: {a} * {b} = {a * b}"

)

       

return

a * b

   

@

staticmethod

   

def

cmp

(

a

,

b

)

:

        result

=

(

a

==

b

)

       

print

(

f

" [ALU] Comparison: {a} == {b} ? {'Yes' if result else 'No'} (Z={1 if result else 0})"

)

       

return

result

============================

5. FullComputer - the complete computer

============================

class

FullComputer:

   

"""
    A complete von Neumann computer simulator.

    Components:
    - disk: hard disk (persistent storage)
    - memory: main memory
    - cache: L1 cache
    - registers: register file (including PC, IR, MAR, MDR, FLAGS)
    - alu: arithmetic logic unit
    - bus: system bus (address + data + control)
    - dma: DMA controller

    Execution flow:
    1. Load: DMA moves the program from disk to memory
    2. Loop: fetch -> decode -> execute -> write back
    3. Generate the complete execution report
    """

   

def

init

(

self

)

:

       

print

(

"="

60

)

       

print

(

" FullComputer - von Neumann computer initializing..."

)

       

print

(

"="

60

)

       

Four-layer storage system

       

self

.

disk

=

Disk

(

)

       

self

.

memory

=

Memory

(

)

       

self

.

cache

=

Cache

(

num_lines

=

8

)

       

self

.

registers

=

RegisterFile

(

)

       

Compute unit

       

self

.

alu

=

ALU

(

)

       

Bus system

       

self

.

bus

=

SystemBus

(

)

       

DMA controller

       

self

.

dma

=

DMAController

(

self

.

bus

)

       

Statistics

       

self

.

instructions_executed

=

0

       

self

.

clock_cycles

=

0

       

print

(

" Components ready: disk, memory (64KB), cache (8-line L1), 4 general-purpose registers"

)

       

print

(

" Components ready: ALU, system bus, DMA controller"

)

       

print

(

)

   

def

store_program

(

self

,

name

,

program

)

:

       

"""Store the program onto the disk"""

       

print

(

f

"[Step 0] Store program '{name}' onto disk"

)

       

self

.

disk

.

store_program

(

name

,

program

)

       

print

(

)

   

def

load_program

(

self

,

program_name

,

load_addr

=

0

)

:

       

"""
        Load program: DMA moves it from disk to memory.
        """

       

print

(

f

"[Step 1] DMA loads program into memory"

)

        size

=

self

.

dma

.

transfer_program

(

           

self

.

disk

,

program_name

,

self

.

memory

,

load_addr

       

)

       

print

(

)

       

Prefetch instructions into cache

       

print

(

f

"[Step 2] Cache warm-up: prefetch the first {min(4, size)} instructions"

)

       

self

.

dma

.

cache_prefetch

(

self

.

memory

,

self

.

cache

,

load_addr

,

min

(

4

,

size

)

)

       

print

(

)

       

Set the PC to the program start address

       

self

.

registers

.

PC

=

load_addr

       

print

(

f

"[Step 3] Set PC <- {load_addr} (program start address)"

)

       

print

(

)

   

def

fetch

(

self

)

:

       

"""
        Stage 1: Fetch
        - Put the PC value into MAR
        - Send the address via the address bus
        - Issue a READ signal via the control bus
        - Get the instruction from the data bus (via the cache layer)
        - Store the instruction into IR
        - PC auto-increments
        """

       

print

(

f

"--- Stage 1: Fetch ---"

)

       

self

.

clock_cycles

=

1

       

MAR ← PC

       

self

.

registers

.

MAR

=

self

.

registers

.

PC

       

print

(

f

"  MAR ← PC = {self.registers.PC}"

)

       

Read memory via the bus (through the cache)

        instruction

=

self

.

bus

.

cpu_read

(

           

self

.

registers

.

MAR

,

self

.

memory

,

self

.

cache

       

)

       

MDR <- data bus, IR <- MDR

       

self

.

registers

.

MDR

=

instruction

       

self

.

registers

.

IR

=

instruction

       

print

(

f

"  MDR ← {instruction}, IR ← MDR"

)

       

PC auto-increments

        old_pc

=

self

.

registers

.

PC

       

self

.

registers

.

PC

=

1

       

print

(

f

"  PC ← {old_pc} + 1 = {self.registers.PC}"

)

       

return

instruction

   

def

decode

(

self

)

:

       

"""
        Stage 2: Decode
        - The controller parses the instruction in IR
        - Separate the opcode and operands
        - Decide the operation for the execute stage
        """

       

print

(

f

"--- Stage 2: Decode ---"

)

       

self

.

clock_cycles

=

1

        instruction

=

self

.

registers

.

IR

        parts

=

instruction.

split

(

)

        opcode

=

parts

[

0

]

        operands

=

parts

[

1

:

]

if

len

(

parts

)

1

else

[

]

       

print

(

f

" Instruction: '{instruction}'"

)

       

print

(

f

" Opcode: {opcode}, operands: {operands}"

)

       

return

opcode

,

operands

   

def

execute

(

self

,

opcode

,

operands

)

:

       

"""
        Stage 3: Execute
        - Perform the corresponding operation based on the opcode
        - The ALU takes part in arithmetic/logical operations
        - May modify registers or set flag bits
        """

       

print

(

f

"--- Stage 3: Execute ---"

)

       

self

.

clock_cycles

=

1

       

if

opcode

==

'LOAD'

:

           

LOAD reg value: load immediate into register

            reg

,

value

=

operands

[

0

]

,

int

(

operands

[

1

]

)

           

self

.

registers

.

gpr

[

reg

]

=

value

           

print

(

f

" Operation: load immediate {value} -> register {reg}"

)

           

print

(

f

" ALU not involved (direct load)"

)

       

elif

opcode

==

'STORE'

:

           

STORE reg addr: store register value into memory

            reg

,

addr

=

operands

[

0

]

,

int

(

operands

[

1

]

)

            value

=

self

.

registers

.

gpr

[

reg

]

           

print

(

f

" Operation: prepare to store value {value} of register {reg} into memory address {addr}"

)

           

The data is ready; the write-back stage performs the actual store operation

           

return

(

'STORE'

,

reg

,

addr

,

value

)

       

elif

opcode

==

'ADD'

:

           

ADD dst src: dst = dst + src

            dst

,

src

=

operands

[

0

]

,

operands

[

1

]

            old_val

=

self

.

registers

.

gpr

[

dst

]

            result

=

self

.

alu

.

add

(

old_val

,

self

.

registers

.

gpr

[

src

]

)

           

self

.

registers

.

gpr

[

dst

]

=

result

           

Set the zero flag

           

self

.

registers

.

FLAGS

[

'Z'

]

=

(

result

==

0

)

           

print

(

f

" Operation: {dst} <- {old_val} + {self.registers.gpr.get(src, src)} = {result}"

)

           

print

(

f

" Zero flag Z <- {self.registers.FLAGS['Z']}"

)

       

elif

opcode

==

'SUB'

:

           

SUB dst src: dst = dst - src

            dst

,

src

=

operands

[

0

]

,

operands

[

1

]

            old_val

=

self

.

registers

.

gpr

[

dst

]

            result

=

self

.

alu

.

sub

(

old_val

,

self

.

registers

.

gpr

[

src

]

)

           

self

.

registers

.

gpr

[

dst

]

=

result

           

self

.

registers

.

FLAGS

[

'Z'

]

=

(

result

==

0

)

           

print

(

f

" Operation: {dst} <- {old_val} - {self.registers.gpr.get(src, src)} = {result}"

)

       

elif

opcode

==

'MUL'

:

           

MUL dst src: dst = dst * src

            dst

,

src

=

operands

[

0

]

,

operands

[

1

]

            old_val

=

self

.

registers

.

gpr

[

dst

]

            result

=

self

.

alu

.

mul

(

old_val

,

self

.

registers

.

gpr

[

src

]

)

           

self

.

registers

.

gpr

[

dst

]

=

result

           

self

.

registers

.

FLAGS

[

'Z'

]

=

(

result

==

0

)

           

print

(

f

" Operation: {dst} <- {old_val} * {self.registers.gpr.get(src, src)} = {result}"

)

       

elif

opcode

==

'CMP'

:

           

CMP a b: compare two register values and set the zero flag

            a

,

b

=

operands

[

0

]

,

operands

[

1

]

            is_equal

=

self

.

alu

.

cmp

(

               

self

.

registers

.

gpr

[

a

]

,

               

self

.

registers

.

gpr

[

b

]

           

)

           

self

.

registers

.

FLAGS

[

'Z'

]

=

is_equal

       

elif

opcode

==

'JMP'

:

           

JMP addr: unconditional jump

            target

=

int

(

operands

[

0

]

)

           

print

(

f

" Operation: unconditionally jump to address {target}"

)

            old_pc

=

self

.

registers

.

PC

           

self

.

registers

.

PC

=

target

           

print

(

f

" PC <- {old_pc} -> {target} (jump)"

)

       

elif

opcode

==

'JZ'

:

           

JZ addr: jump if the zero flag is true

            target

=

int

(

operands

[

0

]

)

           

if

self

.

registers

.

FLAGS

[

'Z'

]

:

               

print

(

f

" Operation: zero flag is true (Z=1), jump to address {target}"

)

               

self

.

registers

.

PC

=

target

           

else

:

               

print

(

f

" Operation: zero flag is false (Z=0), no jump, execute sequentially"

)

       

elif

opcode

==

'HALT'

:

           

HALT: halt

           

print

(

f

" Operation: halt instruction, program ends"

)

           

return

'HALT'

       

else

:

           

print

(

f

" Unknown opcode: {opcode}"

)

       

return

None

   

def

writeback

(

self

)

:

       

"""
        Stage 4: WriteBack
        - If there is an operation that needs to write back to memory (such as STORE), it is completed in this stage
        - Transfer data via the data bus
        """

       

print

(

f

"--- Stage 4: WriteBack ---"

)

       

self

.

clock_cycles

=

1

       

For general instructions, the result has already been written into the register during the execute stage

       

The STORE instruction needs to write memory in this stage

       

print

(

f

" Register state: {self.registers.gpr}"

)

       

print

(

f

" Flag register: {self.registers.FLAGS}"

)

   

def

writeback_store

(

self

,

addr

,

value

)

:

       

"""Write-back operation of the STORE instruction--write to memory via the bus"""

       

self

.

bus

.

cpu_write

(

addr

,

value

,

self

.

memory

)

       

print

(

f

" STORE complete: {value} -> memory address {addr}"

)

   

def

run

(

self

)

:

       

"""
        Run the loaded program.
        Loop through fetch -> decode -> execute -> write back until the program ends.
        """

       

print

(

"="

60

)

       

print

(

" Program starts executing"

)

       

print

(

"="

60

)

       

while

self

.

registers

.

PC

<

max

(

self

.

memory

.

cells

.

keys

(

)

,

default

=

0

)

1

:

           

Check whether the PC is within the valid range

           

if

self

.

registers

.

PC

not

in

self

.

memory

.

cells

:

               

PC is out of the program range, possibly because it jumped to the end; finish

               

print

(

f

"\n Program counter PC={self.registers.PC} is out of program range, execution ends"

)

               

break

           

self

.

instructions_executed

=

1

           

print

(

f

"\n{'#' * 55}"

)

           

print

(

f

"### Instruction #{self.instructions_executed} | PC = {self.registers.PC}"

)

           

print

(

f

"{'#' * 55}"

)

           

Fetch

            instruction

=

self

.

fetch

(

)

           

Decode

            opcode

,

operands

=

self

.

decode

(

)

           

Executing

            special

=

self

.

execute

(

opcode

,

operands

)

           

Handle the HALT instruction

           

if

special

==

'HALT'

:

               

self

.

clock_cycles

=

1

               

break

           

Write Back

           

if

special

and

special

[

0

]

==

'STORE'

:

                _

,

reg

,

addr

,

value

=

special

               

self

.

writeback_store

(

int

(

addr

)

,

value

)

           

else

:

               

self

.

writeback

(

)

           

Safety check: prevent infinite loops

           

if

self

.

instructions_executed

1000

:

               

print

(

"\n Warning: over 1000 instructions executed, forced stop (possible infinite loop)"

)

               

break

       

print

(

f

"\n{'=' * 60}"

)

       

print

(

f

" Program execution finished"

)

       

print

(

f

"{'=' * 60}"

)

   

def

report

(

self

)

:

       

"""
        Generate the complete execution report.
        Summarize all statistics: cache hit rate, instruction count, clock cycles,
        bus transfer count, memory read/write counts, etc.
        """

       

print

(

f

"\n{'=' * 65}"

)

       

print

(

f

" FullComputer execution report -- RUNOOB"

)

       

print

(

f

"{'=' * 65}"

)

       

print

(

)

       

Basic information

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Basic information"

)

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Total instructions executed: {self.instructions_executed:>6d}"

)

       

print

(

f

" Total clock cycles: {self.clock_cycles:>6d}"

)

       

if

self

.

instructions_executed

0

:

            cpi

=

self

.

clock_cycles

/

self

.

instructions_executed

           

print

(

f

" Average CPI (cycles/instruction): {cpi:>6.2f}"

)

       

print

(

)

       

Cache performance

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Cache performance (L1 Cache)"

)

       

print

(

f

"  {'─' * 55}"

)

        total_access

=

self

.

cache

.

hit_count

self

.

cache

.

miss_count

       

print

(

f

" Cache hits: {self.cache.hit_count:>6d} times"

)

       

print

(

f

" Cache misses: {self.cache.miss_count:>6d} times"

)

       

print

(

f

" Total accesses: {total_access:>6d} times"

)

       

print

(

f

" Hit rate: {self.cache.hit_rate:>6.1f}%"

)

       

print

(

f

" Total cache lines: {self.cache.num_lines:>6d}"

)

       

print

(

)

       

Memory access

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Memory access statistics"

)

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Memory read operations: {self.memory.read_count:>6d} times"

)

       

print

(

f

" Memory write operations: {self.memory.write_count:>6d} times"

)

       

print

(

f

" Total memory accesses: {self.memory.read_count + self.memory.write_count:>6d} times"

)

       

print

(

f

" Used memory addresses: {len(self.memory.cells):>6d}"

)

       

print

(

)

       

Bus statistics

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Bus statistics"

)

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Bus transfers initiated by CPU: {self.bus.transfer_count:>6d} times"

)

       

print

(

f

" Bus transfers initiated by DMA: {self.dma.transfer_count:>6d} times"

)

        total_bus

=

self

.

bus

.

transfer_count

self

.

dma

.

transfer_count

       

print

(

f

" Total bus transfers: {total_bus:>6d} times"

)

       

print

(

)

       

Final register state

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Final register state"

)

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" General-purpose registers: {self.registers.gpr}"

)

       

print

(

f

" Program counter PC: {self.registers.PC}"

)

       

print

(

f

" Instruction register IR: {self.registers.IR}"

)

       

print

(

f

" Flag register FLAGS: {self.registers.FLAGS}"

)

       

print

(

)

       

Memory data dump (only data at valid addresses is shown)

       

print

(

f

"  {'─' * 55}"

)

       

print

(

f

" Memory data dump (program area only)"

)

       

print

(

f

"  {'─' * 55}"

)

       

if

self

.

memory

.

cells

:

           

for

addr

in

sorted

(

self

.

memory

.

cells

.

keys

(

)

)

:

                val

=

self

.

memory

.

cells

[

addr

]

               

print

(

f

" Address {addr:>4d} (0x{addr:04X}): {val}"

)

       

else

:

           

print

(

f

" (Memory is empty)"

)

       

print

(

)

       

print

(

f

"{'=' * 65}"

)

       

print

(

f

" End of report. Thanks for using the RUNOOB FullComputer simulator!"

)

       

print

(

f

"{'=' * 65}"

)

============================

6. Main program - end-to-end demo

============================

if

name

==

"main"

:

   

print

(

)

   

print

(

"╔"

"═"

58

"╗"

)

   

print

(

"║"

" The complete journey of an instruction -- RUNOOB FullComputer demo "

.

center

(

52

)

"║"

)

   

print

(

"╚"

"═"

58

"╝"

)

   

print

(

)

   

Create a computer

    computer

=

FullComputer

(

)

   

Define demo program: compute (10 + 7) * 2 - 3 = ?

   

Use LOAD to load initial values, use ADD/MUL/SUB to complete the calculation

    demo_program

=

[

       

"LOAD A 10"

,

   

A = 10

       

"LOAD B 7"

,

   

B = 7

       

"ADD A B"

,

     

A = A + B = 17

       

"LOAD C 2"

,

   

C = 2

       

"MUL A C"

,

     

A = A * C = 34

       

"LOAD D 3"

,

   

D = 3

       

"SUB A D"

,

     

A = A - D = 31

       

"STORE A 100"

,

 

Store the result into memory address 100

       

"LOAD B 31"

,

   

B = 31 (expected result)

       

"CMP A B"

,

     

Compare A and B -> should be equal

       

"JZ 12"

,

       

If equal (Z=1), jump to HALT

       

"LOAD D 0"

,

   

(not executed) D = 0

       

"HALT"

,

       

Halt

   

]

   

Step 1: store the program to disk

    computer.

store_program

(

"RUNOOB_DEMO"

,

demo_program

)

   

Step 2: DMA loads into memory

    computer.

load_program

(

"RUNOOB_DEMO"

,

load_addr

=

0

)

   

Step 3: run the program

    computer.

run

(

)

   

Step 4: print the full execution report

    computer.

report

(

)

   

print

(

f

"\n"

)

   

print

(

f

" Knowledge Review: this demo covers all six modules of computer organization:"

)

   

print

(

f

" Module 1 (Binary): instructions and data are stored in memory encoded in binary"

)

   

print

(

f

" Module 2 (Logic Gates): ADD/SUB/MUL in the execution stage are done by ALU gate circuits"

)

   

print

(

f

" Module 3 (von Neumann): program and data share memory, the five components work together"

)

   

print

(

f

" Module 4 (CPU Principles): PC fetch -> IR decode -> ALU execute -> write-back, the complete four stages"

)

   

print

(

f

" Module 5 (Storage System): disk -> memory -> cache -> register, a four-level storage hierarchy"

)

   

print

(

f

" Module 6 (Bus and I/O): three-bus interaction, DMA program loading, interrupt notification"

)

   

print

(

)


Interpreting the execution report

After running the code above, FullComputer outputs a detailed execution report. Let us interpret its key metrics:

Cache hit rate

The cache hit rate shown in the report reflects the program's temporal and spatial locality. Since our demo program is small and DMA prefetched the first 4 instructions, the hit rate will be high. In real large programs, the cache hit rate is usually above 90% - exactly the point of having a cache.

CPI (cycles per instruction)

In our simplified simulation, each instruction takes a fixed 4 clock cycles (fetch-decode-execute-write-back), so CPI is about 4. Modern CPUs use pipelining to bring CPI down close to 1 - that is, completing one instruction per clock cycle.

Number of bus transfers

Number of bus transfers = transfers initiated by CPU + transfers initiated by DMA. DMA does many transfers during program loading, and the CPU issues at least one read transfer during the fetch stage of each instruction.


What we learned - a six-week course review

Six weeks ago we started from the simplest question, "why do computers only understand 0 and 1". Now we can build a complete computer simulator from scratch. Let us walk through this learning path again:

Week module Key takeaways
Week 1 Binary and information representation Understood why computers use binary, how to convert between number bases, and how all kinds of information (numbers, text, images) are encoded into 0 and 1
Week 2 Logic gates and digital circuits Mastered the three basic gates AND, OR, NOT, and understood how to build adders and an ALU from them
Week 3 von Neumann architecture Understood the division of labor among the five components (arithmetic unit, control unit, memory, input, output) and the "stored-program" concept
Week 4 CPU principles Mastered the four stages of the instruction cycle: fetch-decode-execute-write-back, and how pipelining improves efficiency
Week 5 Storage system Understood the four-level storage pyramid from registers to disk, and how caches use the principle of locality to speed up access
Week 6 Bus and I/O Mastered how the three buses (address/data/control) work together and the efficiency differences among the three I/O methods (polling/interrupt/DMA)

From theory to practice: where to go next

This course has laid a solid foundation in computer organization for you. If you want to dig deeper, here are some recommended directions:


Summary and final check

In one sentence:A computer is not magic - it is abstraction carefully designed layer upon layer, starting from transistor switches and gradually building up logic gates, ALU, CPU, memory system, and buses, finally forming a general-purpose machine that can execute any program. Understand these layers and you truly understand the computer.

Course comprehensive self-test questions

  1. In the FullComputer simulator, during the execution of a LOAD instruction, in which steps are the address bus, data bus, and control bus each used?
  2. If FullComputer's cache had only 4 lines (instead of 8), what effect would that have on program execution efficiency? What is this phenomenon called in computer architecture?
  3. In what scenarios do modern operating systems use polling, interrupt, and DMA? Give one example of each that you can observe in daily computer use.

Reference answers: 1. Fetch stage: the address bus carries the PC value (instruction address), the control bus sends a READ signal, and the data bus returns the instruction content. 2. More cache conflicts and a lower hit rate (called cache thrashing or conflict misses). 3. Polling: progress checks during firmware updates of some simple embedded devices; interrupt: each keypress triggers an interrupt; DMA: large file copies, graphics card framebuffer transfers.