一个多道批处理系统中仅有 P1 和 P2 两个作业,P2 比 P1 晚 5ms 到达, 它们的计算和 I/O 操作顺序如下。
P1 :计算 60ms,I/O 操作 80ms,计算 20ms。
P2 :计算 120ms,I/O 操作 40ms,计算 40ms。 不考虑调度和切换时间,计算完成两个作业需要的最少时间和cpu利用率。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
// 初始化P1和P2进程的计算和I/O操作时间
int p1[] = {60, 80, 20}; // P1的计算和I/O操作序列
int p2[] = {120, 40, 40}; // P2的计算和I/O操作序列
int p1time=0,p2time=0,currentTime=0;
int p1Arrival = 0; // P1的到达时间
int p2Arrival = 5; // P2的到达时间
p2time=p2Arrival;
int totalCPUWorkTime = p1[0]+p2[0]+p1[2]+p2[2]; // CPU工作总时间
// P1开始执行
p1time=p1Arrival+p1[0]+p1[1];//p1cpu+i/o
if(p2Arrival<p1time)//如果p2到达的时间比p1进行完I/O小
{
p2time=max(p2Arrival+p2[0],p1Arrival+p1[0]+p2[0]);//p2进行完cpu时间
cout<<"p1进行完I/O的时间"<<p1time<<" p2进行完第一次cpu的时间 "<<p2time<<endl;
if(p2time>=p1time)//p1不能进行cpu 需要等待
{
p1time=p2time;
}
p1time+=p1[2];//p1继续cpu
p2time+=p2[1];//p2I/O
cout<<"p1进行完的时间"<<p1time<<" p2进行完I/O的时间"<<p2time<<endl;
if(p1time>=p2time)
{
p2time=p1time;
}
p2time+=p2[2];
}
else//如果p2到达的时间比p1进行完I/O大
{
p1time+=p1[2];//p1进行最后一步cpu
cout<<p1time<<" "<<p2time<<endl;
p2time=max(p1time,p2Arrival)+p2[0]+p2[1]+p2[2];
cout<<p1time<<" "<<p2time<<endl;
}
cout<<"p2的总时间"<<p2time<<endl;
currentTime=max(p1time,p2time);
cout << "总时间 " << currentTime << "ms" <<endl;
cout<<totalCPUWorkTime<<" "<<currentTime<<endl;
float cpuUtilization = 100.0f * totalCPUWorkTime / currentTime;
cout << "CPU利用率: " << cpuUtilization << "%" <<endl;
return 0;
}