DEV Community

CodeWizardX1
CodeWizardX1

Posted on

Building a Simple CPU Simulator in Python

Introduction

I created this project for my CS104 course on Codecademy. As part of learning computer architecture, I wanted to understand, on a hands‐on level, how a CPU fetches, decodes, and executes instructions. This simulator demonstrates the fundamentals of CPU registers, memory, and arithmetic instructions in a neat little package—all in Python.


About the Python Code

In this simulator, each instruction (like ADD, SUB, MUL, DIV) is stored in a simple text‐based format ("ADD,R1,R2,R3") inside a memory list. The CPU class then performs the core operations:

  1. Store Values in Registers: It can store integer data in registers before running an instruction.
  2. Fetch: It reads the next instruction from memory, incrementing a program_counter as it goes.
  3. Decode: It splits the instruction string into an opcode (e.g., ADD) and operand registers (like R1, R2, R3) to understand which registers to reference.
  4. Execute: It carries out the arithmetic or logical instruction, modifying the registers as needed.

For example, if the code sees ADD,R5,R1,R2, it takes the values in registers R1 and R2, sums them, and stores the result in R5. It’s a streamlined way to get a feel for how real CPUs handle instructions step by step.

Check out my GitHub repo for the full code and examples: GitHub: CodeWizardX1/cpu_simulator


Conclusion

Building this Python CPU simulator gave me a much better appreciation for how processors orchestrate memory, registers, and instructions. It’s a toy example, but the main concepts—fetch, decode, execute—are the same building blocks used by real hardware. Feel free to explore the repository, try adding new instructions, or extend its capabilities.

Top comments (0)