模拟缓存命中率计算

原题目出处来自这个大佬空间:https://blog.csdn.net/feinifi/article/details/94464696

也是无意中看到,兴趣来了,就想自己也来实现一下

题目:

假设有这样的缓存,如果get到数据返回成功,如果没有get到数据,那么返回失败,不管能否get到数据,总是会把
最新的记录加入缓存,同时缓存有个大小限制,可以无限添加,但是都会把前面的数据挤掉。如果给出缓存大小,
并给出一个查询的列表,用程序模拟这个过程,并求出缓存命中失败的次数。
比如,输入:int size=4,int[] data={1,2,3,4,3,5,3,2,1,5,4}
输出:8

分析:

按照题目的意思,出列规则为先进先出,显然可以用队列来实现这个模拟缓存操作,如果是后进先出则可以用stack栈来实现

话不多说,直接上代码

import java.util.LinkedList;
import java.util.Queue;
/**
* @author wh445306
* @version 1.0
* @Desciption:CacheTest:缓存命中率计算测试题
* @date 2021-01-06 19:21
*/
public class CacheTest {
public static void main(String[] args) {
int size=4;
int iCount=0;
int[] data={1,2,3,4,3,5,3,2,1,5,4};
Queue<Integer> queue = new LinkedList<>();
for (int i=0; i<data.length;i++) {
iCount +=queue.contains(data[i]) ? 1:0;
if (queue.size() >= size) {
queue.remove();
queue.add(data[i]);
} else {
queue.add(data[i]);
}
}
//遍历队列
for(int q : queue){
System.out.println(q);
}
System.out.printf("缓存命中次数:%d 命中率为:%6.2f%% \n",iCount,(double)iCount/data.length*100);
System.out.printf("缓存失败次数:%d 失败率为:%6.2f%% \n",data.length-iCount,(double)(data.length-iCount)/data.length*100);
}
}

执行效果:

posted @   IT情深  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示