The goal of this project was to create a simulation of a CPU written in Python code. I've created classes and functions that relate to the functionalities of a CPU, cache, and memory. Included in the project are two text files that hold the instructions for the CPU and another to hold data values for the memory_bus.
The first class built was the CPU, it contains the an instance variable of cache and memory bus. The CPU has functions of read and write that allow the CPU to read from the cache and write to cache and memory bus.
The second class created was the Cache. The cache has instance variables of size, cache, cache order. I used a dictionary to simulate cache storage and list to keep track of the order of access in cache order. The Cache contains the functions read and write, read will check if the address is in the cache if not it will be a cache miss. The write function will check if the cache is full, if it is then it will evict the least recently used item (LRU). Then write data to cache and track the order.
Third is the MemoryBus class, which contains one instance variable memory and two small functions of read and write.
Fourth is the Memory Class, it contains an instance variable of size, and memory. Memory is initialized to none. The read function will check if the size and address are true and will return the address of the memory. If false, will raise an index error ("Address out of bounds"). The write function follows the same logic except we will save memory address in the data variable.
The last class is the Main class. First I created two functions load_instructions and load_memory_init to fetch and parse instructions and values from both files. The main function is where I loaded the instruction and memory bus file and created instances of all the classes that were created. The next step was to initialize the memory based on the memory bus text file and insert the values and each memory address. Then I look through the instruction text file, split the instructions and return the address as an integer. The next step is to look for the commands written in the instruction text file and to operate on those commands to complete the process. The commands are "FETCH", fetches the address and data value, "ADD" which will fetch and add data from address, and "STORE" that will store data at the address.
This project is a great way to see the functionalities of a CPU, cache, and memory in a simplified way. There are ways to expand on this project which would be to implement an ISA (Instruction Set Architecture) that would use MIPS (Million Instructions Per Second) instructions. Overall, with this project you could gain a simplified understanding of the workings of a CPU.
Thank you for reading,
Here is a link to my code:
https://github.com/dgilson74/CPUSim
Top comments (0)