目的:
熟悉进程调度算法及其实现
内容:
编写一个程序完成多道程序的调度
要求:
只考虑1个CPU的资源,其他资源不考虑
使用响应比高者优先算法
程序采用键盘输入,输入格式为:
K
TJ1 YS1
扫描二维码关注公众号,回复:
11563416 查看本文章
……
TJK YSK
其中K是作业数(>0),TJi提交时间,YSi (i=1~K)是作业预计的运行时间(以分钟计)TJ的输入格式是XXYY,其中XX是时,YY是分,如10点28分,输入为1028。但内部计算要以60进制来算。要求输出按照作业调度的先后次序输出结果,每行为一个作业状态,从左到右分别是调度次序,作业号,调度时间,周转时间和带权周转时间,最后一行输出两个数,第一为平均周转时间,第二为平均带权周转时间。
#include <iostream>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <cstdio>
using namespace std;
int k; //作业数
int pid = 0;
int time = 0; //全局时间
int std2spvn(int t) {
return t%100 + t/100*60;
}
int spvn2std(int t) {
return t/60*100 + t%60;
}
struct PCB {
int id;
int TJ;//提交时间
int YJ;//是作业预计的运行时间
bool end;//进程是否已经完成
float response() const {//进程响应比
if (TJ > time || end == true) return -1;//无法运行的进程返回-1
return (1.0*time-TJ + YJ) / YJ;
}
//TJ的输入格式是XXYY,其中XX是时,YY是分,如10点28分,输入为1028。但内部计算要以60进制来算。
PCB(int m_TJ,int m_YJ) {
id = ++pid;
TJ = std2spvn(m_TJ);
YJ = std2spvn(m_YJ);
end = false;
}
bool operator< (const PCB &tr) const {
return this->response() < tr.response();
}
};
vector<PCB> vecPCB;
/*
要求输出按照作业调度的先后次序输出结果,每行为一个作业状态,
从左到右分别是调度次序,作业号,调度时间,周转时间和带权周转时间,
最后一行输出两个数,第一为平均周转时间,第二为平均带权周转时间。
*/
int main() {
cin >> k;
for (int i = 1,tpTj,tpYs; i <= k; i++) {
cin >> tpTj >> tpYs;
vecPCB.emplace_back(PCB(tpTj,tpYs));
}
float TA_times = 0; //周转时间
float TAW_times = 0; //带权周转时间
for (int i = 1; i <= k; i++) {
PCB &process = *max_element(vecPCB.begin(),vecPCB.end());
if (process.response() < 0) {
puts("调度出错!");
return -1;
}
time = max(time,process.TJ);
int end_time = time+process.YJ;
int TA_time = end_time-process.TJ;
TA_times += TA_time;
int TAW_time = (end_time-process.TJ)/process.YJ;
TAW_times += TAW_time;
printf("调度次序: %d, 作业号: %d 调度时间: %d, 周转时间: %d, 带权周转时间: %d\n", \
i, process.id, time, TA_time, TAW_time);
process.end = true;
time = end_time;
}
printf("平均周转时间: %g, 平均带权周转时间: %g\n", TA_times/k, TAW_times/k);
return 0;
}
/*
5
0000 0010
0001 0001
0002 0002
0003 0001
0004 0005
*/