最佳置换算法

最佳置换算法(OPT):从主存中移出永远不再需要的页面;如无这样的页面存在,则选择最长时间不需要访问的页面。于所选择的被淘汰页面将是以后永不使用的,或者是在最长时间内不再被访问的页面,这样可以保证获得最低的缺页率。 

最佳置换算法可以用来评价其他算法。假定系统为某进程分配了三个物理块,并考虑有以下页面号引用串:
    7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1
进程运行时,先将7, 0, 1三个页面依次装入内存。进程要访问页面2时,产生缺页中断,根据最佳置换算法,选择第18次访问才需调入的页面7予以淘汰。然后,访问页面0时,因为已在内存中所以不必产生缺页中断。访问页面3时又会根据最佳置换算法将页面1淘汰……依此类推,如图所示。从图中可以看出釆用最佳置换算法时的情况。

访问页面70120304230321201701
物理块17772 2 2  2  2   7  
物理块2 000 0 4  0  0   0  
物理块3  11 3 3  3  1   1  
#include<iostream>
#include<list>
#include<vector>
#include<iterator>
#include<fstream>
#include<algorithm>
using namespace std;

class Optimal
{
public:
	int index;
	int dis;
public:
	friend istream & operator>>(istream & i, Optimal&o);
	friend ostream & operator<<(ostream &s, const Optimal&o);
	Optimal(int i)
	{
		this->index = i;
		dis = 0;
	}
	Optimal()
	{
		dis = 0;
	}
	~Optimal()
	{

	}
	bool operator<(Optimal&s)
	{
		if (this->dis < s.dis)
			return true;
		return false;
	}
	bool operator>(Optimal&s)
	{
		if (this->dis > s.dis)
			return true;
		return false;
	}
	bool operator==(const Optimal&s)
	{
		if (this->dis==s.dis  )
			return true;
		return false;
	}
};
istream & operator>>(istream & i, Optimal&o)
{
	i >> o.index;
	return i;
}
ostream & operator<<(ostream &s,const  Optimal&o)
{

	s <<"["<<o.index << "\t" <<"下次位置:"<<o.dis <<"]";

	return s;
}

void main()
{
	fstream out("data.txt");
	list<Optimal> v;
	list<Optimal> w;
	copy(istream_iterator<Optimal>(out), istream_iterator<Optimal>(), back_inserter(v));
	//copy(v.begin(),v.end(),ostream_iterator<Optimal>(cout,"\t"));

	while (v.size())
	{
		if (w.size()<3)
		{
			copy(w.begin(), w.end(), ostream_iterator<Optimal>(cout, "\t"));
			cout << endl;
			Optimal p = v.front();
			v.pop_front();
			w.push_front(p);
		}
		else
		{
			bool istrue = false;
			for (auto ib = w.begin(); ib != w.end(); ib++)
			{
				if (ib->index==v.front().index)
				{
					istrue = true;
				}
			}
			if (istrue == false)
			{
				for (auto ib = w.begin(); ib != w.end(); ib++)
				{
					int x = 0;
					for (auto vib = v.begin(); vib != v.end(); vib++)
					{
						if ((*ib).index == (*vib).index)
						{
							break;
						}
						(*ib).dis = x++;
					}
				}
				copy(w.begin(), w.end(), ostream_iterator<Optimal>(cout, "\t"));
				cout << endl;
				list<Optimal>::iterator s = max_element(w.begin(), w.end());
				w.remove(*s);
				Optimal p = v.front();
				v.pop_front();
				w.push_front(p);
			}
			else
			{
				v.pop_front();
			}
		}
	}
	copy(w.begin(), w.end(), ostream_iterator<Optimal>(cout, "\t"));
	cout << endl;
	cin.get();
}

其中data.txt文件内容为

实验结果是

 

  • 30
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值