CacheSim/set.cpp
2022-01-22 19:30:39 +08:00

107 lines
3.3 KiB
C++

#include "set.h"
#include <iostream>
using std::vector;
using CacheSim::Block;
using CacheSim::Set;
using std::cout;
using std::endl;
Set::Set(short waySize, short tagSize, short replacePolicy){
this->waySize = waySize;
this->emptySize = waySize;
this->replacePolicy = replacePolicy;
for(int i=0; i<waySize; i++){
this->blocks.push_back(Block(tagSize));
}
}
tuple<bool, short> Set::read(vector<bool> tag, short offset){
// HIT 的情況
short baseAccessTime; // 被替換掉的 block ,它的 access time
for(int i=0; i<this->waySize; i++){
if(this->blocks[i].getValid() && this->blocks[i].getTag() == tag){ // valid bit == true 且 tag 相同
if(this->replacePolicy == 1){
baseAccessTime= this->blocks[i].getAccessTime();
this->blocks[i].access();
this->countAccess(baseAccessTime); // 更新計算所有 way access 的時間點
// cout << "HIT: 在 " << i << " way 找到!" << endl;
}
return std::make_tuple(true, i);
}
}
// MISS 的情況,需要寫入 $
short writeWay;
if(this->emptySize > 0){
for(int i=0; i<this->waySize; i++){
if(this->blocks[i].getValid() == false){
// cout << "MISS: 在 " << i <<" way 寫入資料" << endl;
this->blocks[i].update(tag); // 更新 tag
this->blocks[i].access();
writeWay = i;
baseAccessTime = this->waySize; // 每個都要更新
break;
}
}
this->emptySize--;
}else{ // 沒有空位,需要 replace
short maxIndex = -1, maxTime = -1;
short tempTime;
// 找最久沒被 access 的 block index
for(int i=0; i<this->waySize; i++){
tempTime = this->blocks[i].getAccessTime();
if(tempTime > maxTime){
maxTime = tempTime;
maxIndex = i;
}
}
// update
// cout << "MISS: way 滿了,找到 " << maxIndex << " 在 " << maxTime << " 前更新" << endl;
baseAccessTime = this->blocks[maxIndex].getAccessTime();
this->blocks[maxIndex].update(tag);
this->blocks[maxIndex].access();
writeWay = maxIndex;
// for(int i=0; i<this->waySize; i++){
// vector<bool> t = this->blocks[i].getTag();
// for(int j=0; j<t.size(); j++){
// cout << t[j];
// }
// cout << endl;
// }
}
this->countAccess(baseAccessTime);
return std::make_tuple(false, writeWay);
}
void Set::countAccess(short baseAccessTime){
for(int i=0; i<this->waySize; i++){
if(this->blocks[i].getAccessTime() < baseAccessTime){ // 小於 basetime 就 ++,補足 basetime 缺的 hole
this->blocks[i].countAccess();
}
}
// for(int i=0; i<20; i++){
// cout << "=" ;
// }
// cout << "way 狀態";
// for(int i=0; i<20; i++){
// cout << "=";
// }
// cout<<endl;
// for(int i=0; i<this->waySize; i++){
// cout << this->blocks[i].getAccessTime() << " ";
// }
// cout<<endl;
// for(int i=0; i<45; i++){
// cout << "=";
// }
// cout<<endl;
}