1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#include <iostream> #include <vector> #include <unordered_map> const int CACHE_SIZE = 16; // Number of cache lines // CacheLine class class CacheLine { public: int tag; bool valid; int data; CacheLine() : tag(-1), valid(false), data(0) {} }; // Cache class class Cache { public: std::vector<CacheLine> lines; Cache() : lines(CACHE_SIZE) {} int read(int address) { int index = address % CACHE_SIZE; int tag = address / CACHE_SIZE; if (lines[index].valid && lines[index].tag == tag) { // Cache hit std::cout << "Cache hit: Address " << address << " -> Data " << lines[index].data << std::endl; return lines[index].data; } else { // Cache miss std::cout << "Cache miss: Address " << address << std::endl; return -1; } } void write(int address, int data) { int index = address % CACHE_SIZE; int tag = address / CACHE_SIZE; lines[index].tag = tag; lines[index].valid = true; lines[index].data = data; std::cout << "Writing data " << data << " to address " << address << std::endl; } }; int main() { Cache cache; // Writing data to cache cache.write(10, 100); cache.write(26, 200); // This will replace data at address 10 due to direct-mapping // Reading data from cache cache.read(10); // This will be a cache miss cache.read(26); // This will be a cache hit return 0; } |
Explanation:
- CacheLine Class:
tag
: Stores the tag part of the address.valid
: Indicates if the cache line contains valid data.data
: Stores the data.
- Cache Class:
lines
: A vector ofCacheLine
objects representing the cache lines.read(int address)
: Reads data from the cache. Checks if the data is valid and if the tag matches. Reports a cache hit or miss.write(int address, int data)
: Writes data to the cache. Updates the cache line with the new tag and data.
- Main Function:
- Creates a
Cache
object. - Performs write operations to store data in the cache.
- Performs read operations to retrieve data from the cache and demonstrate cache hits and misses.
- Creates a