Building a CPU Simulator in Python: Understanding the Inner Workings of a CPU

MOHAMED IDAGHDOUR
3 min readJun 30, 2024

--

Introduction

Have you ever wondered how a CPU processes instructions and manages memory? As the brain of the computer, the CPU performs billions of calculations every second, executing programs, and ensuring smooth operation of your device. To better understand these fascinating operations, I created a CPU simulator in Python. This project delves into the mechanics of fetching, decoding, and executing instructions, while simulating memory operations and a simple cache mechanism. If you’re keen on learning about CPU architecture or enhancing your Python skills, this simulator is a perfect project to explore!

The Code

The simulator is designed to mimic the functionalities of a CPU, cache, and memory bus. It supports a set of MIPS instructions such as ADD, SUB, and JUMP, providing a practical way to see how these operations are executed. The main components of the simulator are:

  1. CPU: Manages the fetch-decode-execute cycle.
  2. Memory Bus: Simulates memory operations.
  3. Cache: Implements a simple cache mechanism to store frequently accessed data.

Here’s a quick overview of the main Python files in the project:

  • cpu.py: Contains the CPU class that handles instruction fetching, decoding, and execution.
  • memory_bus.py: Contains the MemoryBus class for memory read/write operations.
  • cache.py: Contains the Cache class for simulating cache behavior.
  • app.py: The main application file that ties everything together, initializes the components, loads memory values and instructions, and runs the CPU.

The data_input.txt and instruction_input.txt files contain the initial memory values and program instructions, respectively. The program reads these files, loads the data into memory, and starts executing the instructions.

def main():
"""Initializes the CPU, cache, and memory bus.
Loads initial memory values and program instructions from specified files, loads them into memory, and runs the CPU.
Finally, prints the state of registers and a portion of memory after execution."""

print("Phase 1")

# Initialize components
memory_bus = MemoryBus()
cache = Cache()
cpu = CPU(memory_bus, cache)
print("Phase 2")

# Load initial memory and program
initial_memory = load_memory_from_file('data_input.txt')
program = load_instructions_from_file('instruction_input.txt')
print("Phase 3")
memory_bus.load_memory(initial_memory)

# Uses dictionary comprehension to create a dictionary of memory addresses and program instructions.
memory_bus.load_memory({i + len(initial_memory): program[i] for i in range(len(program))})
print("Phase 4")

# Run the cpu
cpu.run()
print("Phase 5")

# Output the final state
print("Registers: ", cpu.registers)
print("Memory: ", memory_bus.memory[:16])

if __name__ == "__main__":
main()

The main function initializes the CPU, cache, and memory bus, loads the memory and instructions from the files, and runs the CPU. After execution, it prints the state of the registers and a portion of the memory.

Conclusion

This CPU simulator project provides a hands-on approach to understanding the fundamental operations of a CPU. By simulating the fetch-decode-execute cycle and implementing MIPS instructions, you gain a deeper insight into how instructions are processed and executed. Whether you are a student, a hobbyist, or a professional looking to brush up on computer architecture, this simulator is an excellent tool to experiment with.

Check out the full code and start your exploration here: CPU_Simulator_using-pytyhon. Happy coding!

--

--

MOHAMED IDAGHDOUR
0 Followers

Full-stack software developer. Passion for building and rebuilding things. Big believer in self-education and staying updated with latest trends.