设计一个用c++按优先权调度算法实现处理器调度的程序完整代码
时间: 2024-06-19 18:02:37 浏览: 119
以下是一个简单的用C++实现优先权调度算法的处理器调度程序的代码:
```
#include<iostream>
#include<algorithm>
using namespace std;
struct Process {
int pid; // 进程id
int burstTime; // 进程执行时间
int priority; // 进程优先级
};
// 比较函数,按照进程优先级从高到低排序
bool cmp(Process p1, Process p2) {
return p1.priority > p2.priority;
}
int main() {
int n; // 进程数量
cout << "请输入进程数量:";
cin >> n;
Process *processes = new Process[n]; // 动态分配进程数组
// 输入每个进程的信息
for(int i = 0; i < n; i++) {
cout << "请输入进程" << i+1 << "的执行时间和优先级(以空格隔开):";
cin >> processes[i].burstTime >> processes[i].priority;
processes[i].pid = i+1;
}
// 按照进程优先级从高到低排序
sort(processes, processes+n, cmp);
// 计算平均等待时间和平均周转时间
double avgWaitingTime = 0, avgTurnaroundTime = 0;
int waitingTime = 0;
for(int i = 0; i < n; i++) {
avgWaitingTime += waitingTime;
waitingTime += processes[i].burstTime;
avgTurnaroundTime += waitingTime;
}
avgWaitingTime /= n;
avgTurnaroundTime /= n;
// 输出结果
cout << endl << "进程执行顺序:";
for(int i = 0; i < n; i++) {
cout << " P" << processes[i].pid << " ";
}
cout << endl << "平均等待时间:" << avgWaitingTime << endl;
cout << "平均周转时间:" << avgTurnaroundTime << endl;
delete[] processes; // 释放动态分配的内存
return 0;
}
```
阅读全文