湛蓝之海 发表于 2021-12-15 19:20:05

#yyds干货盘点#LRU置换算法

思想:利用局部性原理,根据一个进程在执行过程中过去的页面访问踪迹来推测未来的行为。认为过去一段时间里不曾被访问过的页面,在最近的将来可能也不会再被访问。即利用“最近的过去”预测“最近的将来”。
即选择最近一段时间内最久不用的页面予以淘汰。性能接近最佳算法。
了解页面置换的算法,编写LRU置换算法
假定一个能够存放M个页面的内存,当发生缺页时,调入一个页面,通过LRU算法求出应该置换出的页面号。输入一连串的页面号,程序自动选择调出的页面并计算缺页率。  
LRU算法的实现要归功于一个寄存器的实现
设系统为基本进程分配了三个物理块,且页面使用顺序:
70120304230321201701
使用LRU置换算法:

缺页次数12次,缺页率 = 12/20×100%= 60%
置换9次
那么如何用代码实现呢
chapter02;
public class P176LRU {
    //查找元素是否在数组中存在
    public static int paramExist(int[] place,int param){
      for (int i = 0; i < place.length; i++) {
            if(place==param)
                return i;
      }
      //不为空
      return -1;
    }

    //查找元素是否在数组中存在
    public static void ChangePlaceCount(int[] placeIndex,int NotNeedIndex){
      for (int i = 0; i < placeIndex.length; i++) {
            if(i==NotNeedIndex)
                placeIndex=0;
            else
                placeIndex++;
      }
    }

    //获取最大距离值
    public static int getMaxIndexOfCount(int[] place,int[] placeCount){
      int maxCount = placeCount;
      int maxIndex = 0;
      for(int i = 0;i<placeCount.length;i++){
            if(placeCount>maxCount){
                maxCount = placeCount;
                maxIndex = i;
            }
      }
      return maxIndex;
    }
    public static void main(String[] args) {
      int[] block = new int[]{7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1};
      int max = block.length;
      int[] place = new int[]{-1,-1, -1};
      int[] placeCount = new int[]{max,max,max};
      for (int index = 0; index < block.length; index++) {
            //假设元素存在则不需要进行任何操作
            int exitsIndex = paramExist(place,block);
            if(exitsIndex!=-1){
                //当前existIndex需要清零,其他的需要进行++
                ChangePlaceCount(placeCount,exitsIndex);
                continue;
            }
            //元素不存在,即为-1
            else {
                int maxIndex = getMaxIndexOfCount(place,placeCount);
                place = block;
                ChangePlaceCount(placeCount,maxIndex);
                for (int param : place) {
                  System.out.print(param + " ");
                }
                System.out.println();
            }
      }
    }
}控制台输出:

最近使用的页面数据会在未来一段时期内仍然被使用,已经很久没有使用的页面很有可能在未来较长的一段时间内仍然不会被使用。基于这个思想,会存在一种缓存淘汰机制,每次从内存中找到最久未使用的数据然后置换出来,从而存入新的数据!它的主要衡量指标是使用的时间,附加指标是使用的次数。在计算机中大量使用了这个机制,它的合理性在于优先筛选热点数据,所谓热点数据,就是最近最多使用的数据!因为,利用LRU我们可以解决很多实际开发中的问题,并且很符合业务场景。

            </div>
      
      <div id="asideoffset"></div>

https://blog.51cto.com/u_15403033/4806818
页: [1]
查看完整版本: #yyds干货盘点#LRU置换算法