LRU置换算法

340 阅读2分钟

「这是我参与11月更文挑战的第15天,活动详情查看:2021最后一次更文挑战

思想:利用局部性原理,根据一个进程在执行过程中过去的页面访问踪迹来推测未来的行为。认为过去一段时间里不曾被访问过的页面,在最近的将来可能也不会再被访问。即利用“最近的过去”预测“最近的将来”。

即选择最近一段时间内最久不用的页面予以淘汰。性能接近最佳算法。

了解页面置换的算法,编写LRU置换算法

假定一个能够存放M个页面的内存,当发生缺页时,调入一个页面,通过LRU算法求出应该置换出的页面号。输入一连串的页面号,程序自动选择调出的页面并计算缺页率。  

LRU算法的实现要归功于一个寄存器的实现

设系统为基本进程分配了三个物理块,且页面使用顺序:

7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1

使用LRU置换算法:

image.png

缺页次数12次,缺页率 = 12/20×100%= 60% 置换9次

那么如何用代码实现呢

package chapter02;
public class P176LRU {
    //查找元素是否在数组中存在
    public static int paramExist(int[] place,int param){
        for (int i = 0; i < place.length; i++) {
            if(place[i]==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[i]=0;
            else
                placeIndex[i]++;
        }
    }
 
    //获取最大距离值
    public static int getMaxIndexOfCount(int[] place,int[] placeCount){
        int maxCount = placeCount[0];
        int maxIndex = 0;
        for(int i = 0;i<placeCount.length;i++){
            if(placeCount[i]>maxCount){
                maxCount = placeCount[i];
                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[index]);
            if(exitsIndex!=-1){
                //当前existIndex需要清零,其他的需要进行++
                ChangePlaceCount(placeCount,exitsIndex);
                continue;
            }
            //元素不存在,即为-1
            else {
                int maxIndex = getMaxIndexOfCount(place,placeCount);
                place[maxIndex] = block[index];
                ChangePlaceCount(placeCount,maxIndex);
                for (int param : place) {
                    System.out.print(param + " ");
                }
                System.out.println();
            }
        }
    }
}

控制台输出:

image.png

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