Ifstream
Ifstream
#include <iomanip>
#include <string>
#include <cstdlib>
#include <fstream>
#include <array>
#include <map>
using namespace std;
unsigned long int readaddress(ifstream *);
int main()
{
unsigned long int address;
// key is the hash value ; value is the 2-way instrucion cache index
map<int , array<unsigned long int, 2>> instruction_cache;
instruction_cache[0][0]=-1;
instruction_cache[0][1]=-1;
unsigned int cache_size_KB = 8; //KB
unsigned int block_size = 16; //Byte
unsigned int cache_size_Byte = cache_size_KB * 1024; // Byte
int miss = 0;
int slow_hit = 0;
int fast_hit = 0;
// open the address file
ifstream file("trace.txt", ios::in );
ifstream &inputfilein = file;
while((address=readaddress(&inputfilein))!=-1){
// memory index is the index counted by block size
// without modulo cache size
int memory_index = address / block_size;
int block_index = (address % cache_size_Byte) / block_size;
if(memory_index == instruction_cache[block_index][0]){
fast_hit++;
} else {
if(memory_index == instruction_cache[block_index][1]){
slow_hit++;
// b = a ^ b; a = a ^ b; b = a ^ b -- swap a and b
swap(instruction_cache[block_index][0],
instruction_cache[block_index][1]);
} else {
instruction_cache[block_index][1] =
instruction_cache[block_index][0];
instruction_cache[block_index][0] = memory_index;
miss++;
}
}
}
cout<<"The overall miss number is "<< miss <<endl;
cout<<"The overall hit number is "<< fast_hit + slow_hit <<endl;
cout<<"\tThe fast hit number is "<< fast_hit <<endl;
cout<<"\tThe slow hit number is "<< slow_hit <<endl;
cout<<"The miss rate is "<< (float)miss /(float)(miss + fast_hit + slow_hit)
<<endl;
return 0;
}
// read the address of the next line from the file and convert it into an integer
unsigned long int readaddress(ifstream * inputfile){
unsigned long int address;
if (!(*inputfile)) {
cerr << "File could not be opened" << endl;
exit( 1 );
}
string ReadLine;
if(getline(*inputfile,ReadLine)){
address = strtoul(ReadLine.data(),0,16);
return address;
}
return -1;
}