LRU(最近最少使用淘汰算法)基本实现

时间:2023-12-09 15:50:19

LRU(Least Recently Used)

出发点:在页式存储管理中,如果一页很长时间未被访问,则它在最近一段时间内也不会被访问,即时间局部性,那我们就把它调出(置换出)内存,相反的,如果一个数据刚刚被访问过,那么该数据很大概率会在未来一段时间内访问。

可以使用栈、队列、链表来简单实现,在InnoDB中,使用适应性hash,来实现热点页的查找(因为快速)。

1. 用栈(数组模拟)简单实现访页逻辑:

 #include <iostream>
using namespace std; void conduct(int Size, int Num, int A[]);//处理函数
void print(int a[], int num);//输出函数 int main()
{
int stack_size, num, i, acess[];
cout << "输入栈空间:" ;
cin >> stack_size;
cout << "输入进程数(Max=100):" ;
cin >> num; cout << "输入进程访页顺序:" ;
for(i=; i<num; i++)
{
cin >> acess[i];
} conduct(stack_size, num, acess); return ;
} void conduct(int Size, int Num, int A[])
{
int j, k, Stack[Size];
for(j=; j<Size; j++)
{
cout << "进入:" << A[j] <<endl;
Stack[j]=A[j];//先处理前几个元素
}
int locate;bool flag;
for(j=Size; j<Num; j++)
{
flag=false;
for(k=; k<Size; k++)
{
if(Stack[k]==A[j])
{
flag=true;
locate=k;
}
}
if(flag==true)//有重复
{
cout << "重复进程:" << A[j] <<endl;
cout << "取出再压栈" <<endl;
int tempp;
for(k=locate; k<Size; k++)
{
Stack[k]=Stack[k+];
}
Stack[Size-]=A[j];
cout << "压栈完成" <<endl;
cout << "当前顺序:"; print(Stack, Size);
}
else
{
cout << "非重复,压栈:" << A[j] <<endl;
for(k=; k<Size-; k++)
{
Stack[k]=Stack[k+];
}
Stack[Size-]=A[j];
cout << "置换完成。" <<endl;
cout << "当前顺序:";
print(Stack, Size);
}
}
} void print(int a[], int num)
{
int k;
for(k=; k<num; k++)
{
cout << a[k] << " ";
}
cout << endl;
}
  Code::Blocks 17.12 运行通过!

结果:

LRU(最近最少使用淘汰算法)基本实现

2. 使用lis容器实现LRU逻辑

 #include <iostream>
#include <list>
#include <vector>
using namespace std; class LRU
{
public:
LRU();
~LRU();
void insret(int x);
void printQ();
private:
list<int> lst;
int count;//当前页数
int max_size = ;//最大容纳页数
}; LRU::LRU()
{
this->count = ;
} LRU::~LRU()
{
} //插入算法,先查找,找到先删除再插入;未找到,直接插入
void LRU::insret(int x)
{
cout << "访页:" << x << " ";
auto res = find(lst.begin(), lst.end(), x);
if (res != lst.end())
{
cout << "(exist)" << " ";
lst.erase(res);
lst.push_front(x);
}
else
{
lst.push_front(x);
this->count++;
}
if (this->count > this->max_size)
{
lst.pop_back();
this->count--;
} printQ();
} //打印list
void LRU::printQ()
{
list<int>::iterator it = this->lst.begin();
cout << "当前队列/热点页:";
for (; it != lst.end(); it++)
{
cout << *it << " ";
}
cout << "\ndone. size -- " << this->count << " " << " max_size -- " << this->max_size << endl << endl;
} int main()
{
LRU lru;
vector<int> test = {, , , , , , , , , , , , , , , };
for (int i : test)
lru.insret(i);
return ;
}

结果:

LRU(最近最少使用淘汰算法)基本实现