优先级调度法代码c++
时间: 2023-10-16 07:12:17 浏览: 232
以下是一个简单的 C++ 代码示例,用于实现优先级调度算法:
```
#include<iostream>
using namespace std;
int main()
{
int n, i, j, pos, temp;
float avg_wt, avg_tat;
int bt[20], wt[20], tat[20], p[20];
cout<<"Enter number of process: ";
cin>>n;
cout<<"\nEnter Burst Time and Priority\n";
for(i=0;i<n;i++)
{
cout<<"\nP["<<i+1<<"]\n";
cout<<"Burst Time: ";
cin>>bt[i];
cout<<"Priority: ";
cin>>p[i];
}
//sorting burst time, priority and process number in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(p[j]<p[pos])
pos=j;
}
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=i+1;
i+1=pos;
pos=temp;
}
wt[0]=0; //waiting time for first process is zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
avg_wt+=wt[i];
}
avg_wt/=i;
avg_tat=0;
cout<<"\nProcess\t Burst Time \tWaiting Time\tTurnaround Time";
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avg_tat+=tat[i];
cout<<"\nP["<<i+1<<"]\t\t "<<bt[i]<<"\t\t "<<wt[i]<<"\t\t\t"<<tat[i];
}
avg_tat/=i;
cout<<"\n\nAverage Waiting Time: "<<avg_wt;
cout<<"\nAverage Turnaround Time: "<<avg_tat;
return 0;
}
```
这段代码实现了选择排序算法来按照进程优先级对进程进行排序,计算每个进程的等待时间和平均等待时间以及平均周转时间。
阅读全文