按时间片轮转调度算法c++
时间: 2023-10-18 22:18:13 浏览: 106
以下是一个简单的按时间片轮转调度算法的C++代码实现:
```cpp
#include <iostream>
#include <queue>
using namespace std;
struct Process {
int pid; // 进程ID
int bt; // 执行时间
int at; // 到达时间
int wt; // 等待时间
int tat; // 周转时间
int rt; // 剩余时间
};
void findWaitingTime(Process processes[], int n, int quantum) {
queue<int> q;
int t = 0; // 当前时间点
for (int i = 0; i < n; i++) {
processes[i].rt = processes[i].bt;
}
while (true) {
bool done = true;
for (int i = 0; i < n; i++) {
if (processes[i].rt > 0) {
done = false;
if (processes[i].rt > quantum) {
t += quantum;
processes[i].rt -= quantum;
} else {
t += processes[i].rt;
processes[i].wt = t - processes[i].bt - processes[i].at;
processes[i].rt = 0;
}
q.push(processes[i].pid);
}
}
if (done == true) {
break;
}
}
}
void findTurnAroundTime(Process processes[], int n) {
for (int i = 0; i < n; i++) {
processes[i].tat = processes[i].bt + processes[i].wt;
}
}
void findAvgTime(Process processes[], int n, int quantum) {
int total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, quantum);
findTurnAroundTime(processes, n);
cout << "Processes Burst time Waiting time Turn around time\n";
for (int i = 0; i < n; i++) {
total_wt += processes[i].wt;
total_tat += processes[i].tat;
cout << " " << processes[i].pid << "\t\t" << processes[i].bt << "\t "
<< processes[i].wt << "\t\t " << processes[i].tat << endl;
}
cout << "\nAverage waiting time = " << (float)total_wt / (float)n;
cout << "\nAverage turn around time = " << (float)total_tat / (float)n;
}
int main() {
Process processes[] = {{1, 10, 0, 0, 0, 0},
{2, 5, 0, 0, 0, 0},
{3, 8, 0, 0, 0, 0},
{4, 6, 0, 0, 0, 0},
{5, 3, 0, 0, 0, 0}};
int n = sizeof(processes) / sizeof(processes[0]);
int quantum = 2;
findAvgTime(processes, n, quantum);
return 0;
}
```
其中,`Process`结构体表示一个进程,包括进程ID(`pid`)、执行时间(`bt`)、到达时间(`at`)、等待时间(`wt`)、周转时间(`tat`)和剩余时间(`rt`)。`findWaitingTime`函数实现了按时间片轮转调度算法,计算每个进程的等待时间,`findTurnAroundTime`函数计算每个进程的周转时间。最后,`findAvgTime`函数计算平均等待时间和平均周转时间,并输出每个进程的ID、执行时间、等待时间和周转时间。在`main`函数中,定义了一个进程数组,设置时间片大小为2,调用`findAvgTime`函数计算平均等待时间和平均周转时间。
阅读全文