-
-
Save dannavon/bfcff280e9db886b99001a20e7de0bb0 to your computer and use it in GitHub Desktop.
Cache Analyer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dan Navon - Mamas spring 2023 | |
// | |
#include <iostream> | |
#include <vector> | |
int main() | |
{ | |
const int blocks_per_set = 128; | |
const int num_of_elem = 16; | |
int A[150][200]; | |
for (int i = 0; i < 150; i++) { | |
for (int j = 0; j < 200; j++) { | |
A[i][j] = i * 200 + j; | |
} | |
} | |
int hits = 0; | |
int misses = 0; | |
std::vector<std::vector<std::vector<int>>> Cache(2, std::vector<std::vector<int>>(128, std::vector<int>(16 ,-1))); | |
for (int k = 0; k < 10; k++) { | |
for (int j = 0; j < 200; j++) { | |
for (int i = 0; i < 150; i++) { | |
// Calculate the set index for A[i][j] | |
int address = ((200 * i) + j); | |
int set_index = (address / num_of_elem) % blocks_per_set; | |
int offset = address % num_of_elem; | |
// Check if A[i][j] is present in the cache | |
if (Cache[0][set_index][offset] == A[i][j] || Cache[1][set_index][offset] == A[i][j]) { | |
// Cache hit | |
hits++; | |
} | |
else { | |
// Cache miss | |
misses++; | |
// Bring A[i][j] into the cache | |
if (Cache[0][set_index][offset] == -1) { | |
for (auto h = 0; h < num_of_elem; ++h) { | |
Cache[0][set_index][h] = A[i][j-offset+h]; | |
} | |
} | |
else if (Cache[1][set_index][offset] == -1) { | |
for (auto h = 0; h < num_of_elem; ++h) { | |
Cache[1][set_index][h] = A[i][j - offset + h]; | |
} | |
} | |
else { | |
// Apply LRU replacement policy | |
// Replace the least recently used block in the set | |
// Update the cache entry with A[i][j] | |
// Note: Since the code example doesn't specify the LRU replacement policy implementation, | |
// we'll assume a simple swapping of the least recently used block with the new block. | |
int lru_block = ((address/ num_of_elem) / blocks_per_set) % 2; // Determine the LRU block based on the set index | |
for (auto h = 0; h < num_of_elem; ++h) { | |
Cache[lru_block][set_index][h] = A[i][j - offset + h]; | |
} | |
} | |
} | |
} | |
} | |
} | |
// Calculate the hit rate | |
float hit_rate = static_cast<float>(hits) / (hits + misses) * 100.0; | |
printf("hit rate:%f", hit_rate); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment