DEV Community

Ando
Ando

Posted on

Why I Built This

I Built a CPU From Scratch in Python — And Finally Understood How Computers Think

When I started CS104: Computer Architecture on Codecademy, I realized I had been using computers for years without actually understanding what happens inside. We type print("hello") and it works — but how?

The portfolio project challenge was: "Research, design, and build a Python program that simulates the functionalities of a CPU."

So I decided to stop being a user and start being a builder. Instead of just reading about registers and memory buses, I built them.

The Result (Proof it Works)

Here's my CPU simulator running a real program that adds two numbers, stores them to memory, and tests branching:

![My CPU simulator running in terminal - showing Fetch Decode Execute cycles]

This is my actual terminal output after fixing the import errors (you can see the full journey in my GitHub commits!):

  • It loads instructions from instruction_input.txt
  • It loads initial memory values from data_input.txt
  • It runs 11 cycles of FETCH → DECODE → EXECUTE → WRITEBACK
  • It even tracks Cache Hits/Misses — in this run, 100% hit rate!

And here's the architecture I designed:

![CPU Architecture Diagram]
(Diagram: Instruction and Data flow from input files through CPU → Cache → MemoryBus)

How My Python Code Works

I split the simulator into 3 classes to mimic real hardware, just like Codecademy suggested:

1. MemoryBus (The RAM)

  • 256 addressable locations
  • Methods read(address) and write(address, value)
  • Can load initial values from a CSV file like 10,100 meaning MEM[10] = 100

2. Cache (The Speed Bridge)

  • Simple direct-mapped cache with 8 blocks
  • Write-through policy
  • Tracks hits and misses — crucial for understanding why cache matters in real CPUs
  • If data is not in cache (MISS), it fetches from MemoryBus

3. CPU (The Brain)

  • 8 registers R0-R7 (R0 is hardwired to 0, just like in MIPS)
  • Program Counter (PC) to track next instruction
  • Full Fetch-Decode-Execute loop:
  def fetch(self):
      instr = self.instructions[self.PC]
      print(f"[FETCH] PC={self.PC} | {instr}")
      return instr
Enter fullscreen mode Exit fullscreen mode
  • ISA I implemented:
    • ADD Rd,Rs,Rt → Rd = Rs + Rt
    • SUB, MUL, ADDI (with immediate)
    • LW Rd,Addr → Load Word using cache
    • SW Rs,Addr → Store Word
    • BEQ Rs,Rt,Offset → Branch if equal
    • J Target → Jump
    • HALT → Stop

Each cycle prints its stage, so you can literally watch the CPU think. For example:

[FETCH] PC=2 | ADD,R3,R1,R2
[DECODE] Operation: ADD, Args: ['R3', 'R1', 'R2']
[EXECUTE] R3 = R1(10) + R2(20) = 30
[WRITEBACK] Registers: {'R1':10, 'R2':20, 'R3':30}
Enter fullscreen mode Exit fullscreen mode

Check Out The Code

All the code is open source and ready to run. I struggled with Git case-sensitivity on Windows (Cpu.py vs cpu.py) and missing input files — you can see the fix in my commit history!

GitHub: https://github.com/ikaroshunt/cpu_simulator

To run it yourself:

git clone https://github.com/ikaroshunt/cpu_simulator.git
cd cpu_simulator
python main.py
# or if import fails: python main_single.py
Enter fullscreen mode Exit fullscreen mode

Conclusion

Building this CPU simulator taught me more than any textbook could. I finally understand why cache exists (CPU is fast, memory is slow), why R0 is always 0, and how a simple ADD instruction actually travels through fetch, decode, execute.

It was frustrating at first — ModuleNotFoundError, FileNotFoundError, Git saying "not a git repository" — but each error taught me something about real-world development: file structure matters, case matters, and Git is strict.

If you're taking CS104, don't skip this project. Don't just copy a solution. Build it, break it, fix the imports, and watch your own CPU print "SIMULATION FINISHED". There's no better feeling.

This project was built as part of Codecademy's Computer Science Career Path (CS104: Computer Architecture Portfolio Project).


Tools: Python 3, Git, VS Code, Terminal / PowerShell


Top comments (1)

Collapse
 
danielecangi profile image
DaC •

This is a great kind of project to share.
a lot of people in developer communities tend to showcase very advanced systems, so it can be easy to underestimate the value of building something specifically to understand how it works,
keep documenting the journey. Projects like this are useful not only as portfolio pieces, but also as a record of how your understanding evolves over time🥳