H. A Cache Simulator

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 100100 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 ENDEND.

Output Format

Report either HitHit or MissMiss 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%

题目来源

2017 ACM-ICPC 亚洲区(南宁赛区)网络赛

题意:

模拟一个Cache, Cache的大小是1KB,每一块大小是16B,一共64块,采用direct mapped方式,主存大小是256MB;

思路:

因为计组成原理还没学到这,就现场学习了一下,有关direct mapped方式可以参考https://wenku.baidu.com/view/7ea3d85e10661ed9ad51f3f3.html?from=search,只要理解了direct mapped方式之后这题就好写了,用公式建立主存和Cache之间的联系,Cache一共64块,公式就是I = (address / 16% 64;

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<map>

using namespace std;

const int M = 16 + 5;

map<int, string> mp;
char ch[M];

int main(){
    int total = 0, hit = 0;
    while(scanf("%s", ch) == 1 && strcmp(ch, "END")){
        int sum = 0;
        sscanf(ch, "%x", &sum);
        total ++;
        int I = (sum / 16) % 64;
        ch[6] = '';
        if(mp[I] == ch){
            hit ++;
            printf("Hit
");
        }else{
            mp[I] = ch;
            printf("Miss
");
        }
    }
    printf("Hit ratio = %.2f%%
",double(hit*100.0/ total));
}
原文地址:https://www.cnblogs.com/Pretty9/p/7592984.html