1. 程式人生 > >最近最久未使用(LRU)置換演算法

最近最久未使用(LRU)置換演算法

最近最久未使用演算法(Last Recently Used,LRU)的字面意思即為選擇最近最長時間未訪問過的頁面予以淘汰,它認為過去一段時間未被訪問過的頁面,在最近的將來可能也不會被訪問。該演算法為每個頁面設定一個訪問欄位,來記錄頁面自上次被訪問以來所經歷的時間,淘汰頁面時,選擇現有頁面中值最大的予以淘汰。

下面給出頁面中最多含有5塊記憶體大小的演算法的實現程式碼:

public class LRU {  
  
    private int theArray[];  
    private int back;      //定義隊尾  
    private int currentSize;     //佇列中存放元素個數  
    private int maxSize=5;       //佇列中能存放元素的個數  
     
    public LRU(){  
        theArray=new int[maxSize];  
        back=0;  
        currentSize=0;  
    }  
    public void queue(int a[]){  
        for(int i = 0;i < a.length;i++){  
            enQueue(a[i]);  
        }  
    }  
      
    public void enQueue(int x){           //入隊  
        beUsed(x);                        //先判斷是否已存在該頁號,若存在,刪除  
        if(currentSize < maxSize){  
            theArray[back] = x;  
            back++;   
            currentSize++;  
        }else if(currentSize == maxSize){             //滿了  
            for(int i = 0;i < maxSize - 1;i++){  
                theArray[i] = theArray[i+1];  
            }  
            theArray[maxSize-1]=x;  
        }  
        for(int i = 0;i < currentSize;i++){  
            System.out.print(theArray[i]);  
        }  
        System.out.println();  
    }  
    public void beUsed(int x){            //判斷是否已存在該頁號,若存在,刪除已有的  
        for(int i = 0;i < currentSize;i++){  
            if(theArray[i] == x){  
                for(int j = i;j < currentSize - 1;j++){  
                    theArray[j] = theArray[j + 1];  
                }  
                currentSize--;  
                back--;  
            }     
        }  
    }  
    public static void main(String[] args) {  
        LRU lru = new LRU();  
        int a[] = {4,7,0,7,1,0,1,2,1,2,6};  
        lru.queue(a);  
    }  
  
}

分析:LRU效能較好,但需要暫存器和棧等硬體的支援,且是堆疊類演算法。

實驗結果如下: