用c语言或c++写一份时间片轮转调度算法的测试代码
时间: 2024-03-01 07:53:14 浏览: 153
时间片轮转调度算法 (C++的)
以下是使用 C++ 语言实现的时间片轮转调度算法的测试代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 定义进程类
class Process {
public:
int pid;
int arrival_time;
int burst_time;
int remaining_time;
Process(int pid, int arrival_time, int burst_time) {
this->pid = pid;
this->arrival_time = arrival_time;
this->burst_time = burst_time;
this->remaining_time = burst_time;
}
};
// 时间片轮转调度算法
pair<double, double> round_robin(vector<Process>& processes, int time_slice) {
int n = processes.size();
int current_time = 0;
int waiting_time = 0;
int turnaround_time = 0;
int total_burst_time = 0;
vector<Process> queue;
for (int i = 0; i < n; i++) {
total_burst_time += processes[i].burst_time;
}
while (true) {
// 将到达时间小于等于当前时间的进程加入队列
for (int i = 0; i < n; i++) {
if (processes[i].arrival_time <= current_time && processes[i].remaining_time > 0) {
queue.push_back(processes[i]);
}
}
if (queue.empty()) {
break;
}
// 取出队首进程执行
Process process = queue.front();
queue.erase(queue.begin());
// 执行一个时间片
if (process.remaining_time > time_slice) {
process.remaining_time -= time_slice;
current_time += time_slice;
} else {
current_time += process.remaining_time;
process.remaining_time = 0;
// 计算等待时间和周转时间
waiting_time += current_time - process.arrival_time - process.burst_time;
turnaround_time += current_time - process.arrival_time;
}
// 将未完成的进程加入队列末尾
if (process.remaining_time > 0) {
queue.push_back(process);
}
}
// 计算平均等待时间和平均周转时间
double avg_waiting_time = (double)waiting_time / n;
double avg_turnaround_time = (double)turnaround_time / n;
return make_pair(avg_waiting_time, avg_turnaround_time);
}
// 测试代码
int main() {
vector<Process> processes = {
Process(1, 0, 10),
Process(2, 1, 5),
Process(3, 2, 8),
Process(4, 3, 6),
Process(5, 4, 9),
};
int time_slice = 2;
pair<double, double> result = round_robin(processes, time_slice);
cout << "平均等待时间:" << result.first << endl;
cout << "平均周转时间:" << result.second << endl;
return 0;
}
```
以上代码实现了一个简单的时间片轮转调度算法,用于处理一组进程,并计算平均等待时间和平均周转时间。你可以根据需求修改进程列表和时间片大小,来测试算法的性能和正确性。
阅读全文