CacheSim/set.cpp

101 lines
2.9 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){
this->waySize = waySize;
this->emptySize = waySize;
for(int i=0; i<waySize; i++){
this->blocks.push_back(Block(tagSize));
}
}
bool 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 相同
baseAccessTime= this->blocks[i].getAccessTime();
this->blocks[i].access();
this->countAccess(baseAccessTime); // 更新計算所有 way access 的時間點
cout << "HIT: 在 " << i << " way 找到!" << endl;
return true;
}
}
// MISS 的情況,需要寫入 $
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();
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();
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 false;
}
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;
}