H. A Cache Simulator

本文介绍了一款基于Direct Mapped方式的缓存模拟器程序设计。该程序用于模拟1KB大小、每块16B的Cache,在256MB主存中运行,并通过输入地址报告命中或未命中情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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] = '\0';
        if(mp[I] == ch){
            hit ++;
            printf("Hit\n");
        }else{
            mp[I] = ch;
            printf("Miss\n");
        }
    }
    printf("Hit ratio = %.2f%%\n",double(hit*100.0/ total));
}

 

转载于:https://www.cnblogs.com/Pretty9/p/7592984.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值