-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCache.h
More file actions
84 lines (83 loc) · 2.74 KB
/
Cache.h
File metadata and controls
84 lines (83 loc) · 2.74 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#ifndef MEMORY_ARCHITECTURE_CACHE_H
#define MEMORY_ARCHITECTURE_CACHE_H
#include "Memory.h"
#include "Tools.h"
#include <vector>
#include <stdexcept>
using namespace std;
class Cache : public Memory {
private:
uint16_t blockSize;
uint64_t numSets;
int associativity;
Replacement policy;
vector<vector<pair<uint64_t, uint64_t>>> sets;
public:
Cache(uint64_t size, int baseDelay, uint16_t blockSize, int assoc, Replacement policy) {
this->size = size;
this->baseDelay = baseDelay;
this->blockSize = blockSize;
this->associativity = assoc;
this->policy = policy;
if (size % (blockSize * assoc) != 0) {
throw std::invalid_argument("Size structure is invalid");
}
this->numSets = size / (blockSize * assoc);
sets.resize(numSets);
}
bool getData(uint64_t address) override {
uint64_t blockAddr = address / blockSize;
uint64_t setIndex = blockAddr % numSets;
uint64_t tag = blockAddr / numSets;
for (int i = 0; i < sets[setIndex].size(); i++) {
if (sets[setIndex][i].second == tag) {
if (policy == LRU) {
sets[setIndex][i].first = unixTime();
}
return true;
}
}
return false;
}
void addBlock(uint64_t address) {
uint64_t blockAddr = address / blockSize;
uint64_t setIndex = blockAddr % numSets;
uint64_t tag = blockAddr / numSets;
if (sets[setIndex].size() < associativity) {
sets[setIndex].push_back({unixTime(), tag});
} else {
replace(address);
}
}
void replaceBlock(uint64_t address) {
uint64_t blockAddr = address / blockSize;
uint64_t setIndex = blockAddr % numSets;
uint64_t tag = blockAddr / numSets;
int victimIndex = 0;
if (policy == LRU) {
uint64_t minTime = sets[setIndex][0].first;
for (int i = 1; i < sets[setIndex].size(); i++) {
if (sets[setIndex][i].first < minTime) {
minTime = sets[setIndex][i].first;
victimIndex = i;
}
}
}
else if (policy == RR) {
victimIndex = random(0, sets[setIndex].size() - 1);
}
if (policy == FIFO) {
sets[setIndex].erase(sets[setIndex].begin());
sets[setIndex].push_back({unixTime(), tag});
} else {
sets[setIndex][victimIndex] = {unixTime(), tag};
}
}
int getDelay() override {
return baseDelay + (random(-2, 2) / 100.0 * baseDelay);
}
void replace(uint64_t address) override {
replaceBlock(address);
}
};
#endif //MEMORY_ARCHITECTURE_CACHE_H