编写RR算法浪费了最多的时间,在编写算法前一定要搞清楚原理。RR算法就是在每一个时刻将要执行之前,判断该时刻加上时间片后是否有新进程进入,如果有,压入队列。这个时间点一定要搞明白才行,才能理解。
如果有流程图的话,更容易写。
#include<iostream>
#include<queue>
#include<vector>
#include<windows.h>
using namespace std;
int q_id = 0;
int stime = 0;
struct Pro
{
bool in;
bool run;
int PID;
int starttime;
int endtime;
int arrivetime;
int servetime;
int needtime;
int T;
float W;
};
class process
{
private:
queue<Pro>Queue;
vector<Pro>V_S;
public:
void create();
void RR();
};
void process::create()
{
Pro item;
item.PID = q_id++;
cout << "input arrive & servetime" << endl;
cin >> item.arrivetime >> item.servetime;
item.needtime = item.servetime;
item.in = 0;
item.run = 0;
V_S.push_back(item);
}
void process::RR()
{
int job, capacity;
float T1 = 0, W1 = 0;
cout << "input job" << endl;
cin >> job;
cout << "input capacity" << endl;
cin >> capacity;
for (int i = 0;i < job;i++)
{
create();
}
V_S[0].in = 1;
V_S[0].run = 1;
V_S[0].starttime = 0;
Queue.push(V_S[0]);
while (!Queue.empty())
{
Pro* p = &Queue.front();
if (p->needtime > capacity)
{
p->needtime -= capacity;
stime += capacity;
for (int i = 0;i < V_S.size();i++)
{
if ((V_S[i].arrivetime <= stime) && (V_S[i].in != 1))
{
if (V_S[i].run != 1)
{
V_S[i].starttime = stime + Queue.size()-1;
}
V_S[i].in = 1;
Queue.push(V_S[i]);
}
}
Queue.push(Queue.front());
Queue.pop();
}
else
{
stime += p->needtime;
for (int i = 0;i < V_S.size();i++)
{
if ((V_S[i].arrivetime <= stime) && (V_S[i].in != 1))
{
if (V_S[i].run != 1)
{
V_S[i].starttime = stime + Queue.size() - 1;
}
V_S[i].in = 1;
Queue.push(V_S[i]);
}
}
p->endtime = stime;
for (int i = 0;i < V_S.size();i++)
{
if (p->PID == V_S[i].PID)
{
V_S[i].endtime = p->endtime;
break;
}
}
p->needtime = 0;
Queue.pop();
}
}
for (int i = 0;i < V_S.size();i++)
{
V_S[i].T = V_S[i].endtime - V_S[i].arrivetime;
V_S[i].W = V_S[i].T / float(V_S[i].servetime);
T1 += V_S[i].T;
W1 += V_S[i].W;
}
T1 = T1 / job;
W1 = W1 / job;
cout << "T1=" << T1 << endl;
cout << "W1=" << W1 << endl;
cout << "PID" << '\t' << "Tin" << '\t' << "Tr" << '\t' << "Ts" << '\t' << "Tc" << '\t' << "T" << '\t' << "W" << endl;
for (int i = 0;i < V_S.size();i++)
{
cout << V_S[i].PID << '\t' << V_S[i].arrivetime << '\t' << V_S[i].servetime << '\t' << V_S[i].starttime << '\t' << V_S[i].endtime << '\t' << V_S[i].T << '\t' << V_S[i].W << endl;
}
}
int main()
{
process example;
example.RR();
system("pause");
return 0;
}
为了验证正确性,在网上选取一个例子(时间片=1和4)