Cache memories have been used widely in current microprocessor systems. In this problem, you are asked to write a program for a cache simulator. The cache has the following metrics:
1. The cache size is 1 KB (K-byte).
2. The cache uses the direct mapped approach.
3. The cache line size is 16 bytes.
4. The cacheable memory size is 256MB.
Your program will report a hit or miss when an address is given to the cache simulator. This is often called trace simulation. Initially, all of the cache lines are in the invalid state. When a memory line is first brought into the cache, the allocated cache entry transits into the valid state. Assume that a miss causes the filling of a whole cache line.
Input Format
Up to 100 lines of address can be given in the file. Each line consists of an address given to the simulator. The address is given in hexadecimal form. We assume that each address references only one byte of data. The input file ends at the line with the word END.
Output Format
Report either Hit or Miss for each of the given addresses. The last line reports cache hit ratio in percentage, that is, the number of hits divided by the number of total addresses given.
样例输入
AAAA000 00010B2 00010BA END
样例输出
Miss Miss Hit Hit ratio = 33.33%
题目来源
题意:模拟一个缓存器……
解题思路:模拟即可
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
typedef long long ll;
int n;
char buf[50];
ll qian[65];
bool fenpei[65];
ll scanhex(){
ll res = 0;
int i=0;while(buf[i]){
res*=16;
res+=(buf[i]>='A'&&buf[i]<='F'?buf[i]-'A'+10:(buf[i]>='a'&&buf[i]<='f'?buf[i]-'a'+10:buf[i]-'0'));
i++;
}
return res;
}
int miscount, hitcount;
int main(){
while(~scanf("%s",buf)){
if(strcmp(buf,"END")==0){
double r = 10000*(hitcount / (double)(miscount+hitcount));
r = round(r);
printf("Hit ratio = %g%%\n",r/100);
return 0;
}else{
ll mem = scanhex();
ll Tag = mem / 1024;
ll Index = (mem / 16) % 64;
if(!fenpei[Index]){
printf("Miss\n");
miscount++;
fenpei[Index]=true;
qian[Index]=Tag;
} else if(qian[Index]!=Tag){
printf("Miss\n");
miscount++;
qian[Index] = Tag;
} else {
printf("Hit\n");
hitcount++;
}
}
}
return 0;
}

本文介绍了一种基于直接映射方式的缓存模拟器的设计与实现。该模拟器使用1KB大小的缓存,每条缓存行16字节,并能够处理256MB的内存地址空间。通过解析内存地址并跟踪缓存命中或缺失状态,模拟器可以有效地展示缓存的行为。
799

被折叠的 条评论
为什么被折叠?



