#include <iostream>
using namespace std;
const int MAX=6; //主存块数不超过6
int FS=0; //缺页中断次数
double FSL=0.00; //缺页中断率
int M[MAX]; //主存中的内容
int n; //主存块数
struct pro
{
int time; //时刻
int P; //页面走向
int F; //缺页中断表示
};
//输入信息函数
void input(pro* p,int N)
{
cout<<"请输入主存块数:";
cin>>n;
cout<<"请输入页面走向:";
for(int i=0; i<N; i++)
{
cin>>p[i].P;
}
}
//输出信息函数
void output(pro* p,int N)
{
cout<<"时刻: ";
for(int i=0; i<N; i++)
{
p[i].time=i+1;
cout<<p[i].time<<" ";
}
cout<<endl<<"缺页中断:";
for(int j=0; j<N; j++)
{
cout<<p[j].F<<" ";
}
cout<<endl<<"缺页中断次数:"<<FS;
cout<<endl<<"缺页中断率:" <<FSL<<"%";
}
//计算缺页中断次数和缺页中断率
void calculate(pro* p,int N)
{
for(int i=0; i<N; i++)
{
FS=p[i].F+FS;
}
FSL=double(FS)/N*100;
}
//FIFO算法
void FIFO(pro* p,int N)
{
for(int i=0; i<N; i++) //按照页面走向循环进入主存
{
if(i<n) //主存未满,新进入的直接存进主存当中
{
M[i]=p[i].P;
p[i].F=1;
}
else //主存已满
{
//检查新进的页面在主存中是否存在
bool exist = false;
for (int j=0;j<3;j++)
{
//如果存在和主存中相同的将exist更改为true,并标记没有发生缺页中断
if (p[i].P==M[j])
{
exist=true;
p[i].F=0;
break;
}
}
//经过上一循环的比对如果exist==false,就更改主存中的信息,并标记发生缺页中断。
if (exist==false)
{
for(int k=0; k<n-1; k++)
{
M[k]=M[k+1];
}
M[n-1]=p[i].P;
p[i].F=1;
}
}
}
}
//LRU算法
void LRU(pro* p,int N)
{
for(int i=0; i<N; i++) //按照页面走向循环进入主存
{
if(i<n) //主存未满,新进入的直接存进主存当中
{
M[i]=p[i].P;
p[i].F=1;
}
else //主存已满
{
//检查新进的页面在主存中是否存在
bool exist = false;
for (int j=0;j<3;j++)
{
//如果存在和主存中相同的将exist更改为true,更改主存中页面顺序并标记没有发生缺页中断
if (p[i].P==M[j])
{
exist=true;
int x=M[j];
for(int k=0; k<n-1; k++)
{
M[k]=M[k+1];
}
M[n-1]=x;
p[i].F=0;
break;
}
}
//经过上一循环的比对如果没有和主存中内容相同的即exist==false,就更改主存中的信息,并标记发生缺页中断。
if (exist==false)
{
for(int k=0; k<n-1; k++)
{
M[k]=M[k+1];
}
M[n-1]=p[i].P;
p[i].F=1;
}
}
}
}
int main()
{
int N;
cout<<"请输入使用算法的时间:";
cin>>N;
pro* p=new pro[N];
input(p,N);
cout<<endl<<"FIFO算法:"<<endl;
FIFO(p,N);
calculate(p,N);
output(p,N);
FS=0; //在进行LRU算法之前先重置缺页中断次数。
cout<<endl<<"LRU算法:"<<endl;
LRU(p,N);
calculate(p,N);
output(p,N);
return 0;
}
FIFO和LRU实现(含代码)
最新推荐文章于 2022-12-21 11:53:19 发布