在linux环境下使用g++进行编译运行
g++ -o b h.cpp
./b
好了,切换到正题,这道题是操作系统老师要求我们用代码实现,本身不复杂,只要思路清晰就行。上题目:
假定4道作业,他们的到达的相对时刻,运行时间(单位为ms,十进制)如表所示.试计算在单道作业多道程序环境下,分别采用FCFS调度算法,SF算法时和HRN算法时,这4道作业的平均周转时间及平均带权周转时间,并指出他们的调度顺序(调度时间忽略不计)
作业号 1 到达时刻 0 运行时间 2.0
作业号 2 到达时刻 0.3 运行时间 0.5
作业号 3 到达时刻 0.5 运行时间 0.1
作业号 4 到达时刻 1 运行时间 0.4。
编程的思路就是 先找出进程运行的顺序,然后三个算法的后续工作就一样了,用几个函数就解决了。
我采用的进程结构体,对于FCFS算法,可以用sort进行排序。
对于SF的话,就是先找出第一个运行的进程,因为是短作业优先,所以还得判断短作业的arrive_time是否在上一个进程运行结束的时间内。
对于HRN,也要找出第一个运行的进程,同样的对于所有剩下的进程而言,求出他们的等待时间,如果等待时间小于0,则变为0,因为他还没到时间运行。
/*
*jin
*/
#include<iostream>
#include<algorithm>
#include<fstream>
#include<cstdio>
using namespace std;
const int maxn = 4;
double t=0,w=0;
struct process{//information of process
int number;
double a_time,r_time,f_time,w_time=0,T,W;
}p[maxn];
bool cmp1(process p1,process p2){ //acorrding of arrive_time
return p1.a_time<=p2.a_time;
}
bool cmp2(process p1,process p2){ //acorrding of running_time
return p1.r_time<=p2.r_time;
}
bool cmp3(process p1,process p2){
return p1.w_time/p1.r_time>p2.w_time/p2.r_time;
}
void print(){ //输出结果
cout<<"调度顺序:";
t=0,w=0;
for(int i=0;i<maxn;++i){
t+=p[i].T;w+=p[i].W;
cout<<p[i].number<<" ";
}
cout<<endl;
cout<<"average time: "<<t/maxn<<", average weight time: "<<w/maxn<<endl;
}
void op(){ //排序之后进行相应参数的计算
for(int i=0;i<maxn;++i){
if(!i){
p[i]. f_time=p[i].r_time; p[i].T=p[i].f_time-p[i].a_time;p[i].W=p[i].T/p[i].r_time;
continue;
} //first process
p[i].f_time=p[i-1].f_time+p[i].r_time;p[i].T=p[i].f_time-p[i].a_time;p[i].W=p[i].T/p[i].r_time;
}
}
void FCFS(process *p){
cout<<"FCFS: "<<endl;
sort(p,p+maxn,cmp1);
op();
print();
}
void SF(process *p){
cout<<"sf:"<<endl;
sort(p,p+maxn,cmp1);int location=0;
while(location<maxn){
if(p[++location].a_time==0){continue ;}
else break;
}
// the location of the number bigger than zero
if(location>1) sort(p,p+location,cmp2);//handle the first
int count=1;double sum_time=0;location=1;
while(count<maxn){
sum_time+=p[count-1].r_time;
//location = upper_bound(p,p+maxn,floor(sum_time))-p;
while(location<maxn){
if(p[location++].a_time<=sum_time) continue;
else break;
}
sort(p+count,p+location,cmp2);
++count;
}
op();
print();
}
void HRN(process *p){
cout<<" HRN: "<<endl;
sort(p,p+maxn,cmp1);
int count=1;
while(count<maxn){
for(int i=count;i<maxn;++i){
p[i].w_time=p[count-1].f_time-p[i].a_time;
if(p[i].w_time<0) p[i].w_time=0;
}
sort(p+count,p+maxn,cmp3);
++count;
}
op();
print();
}
int main(){
FILE *fp=fopen("data.txt","rb");
if(!fp) {cerr<<"no such file\n"; exit(1);}
int nu=0;
while(fscanf(fp,"%d %lf %lf",&p[nu].number,&p[nu].a_time,&p[nu].r_time)!=-1 &&nu<4){
nu++;
}
fclose(fp);
FCFS(p);
SF(p);
HRN(p);
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容