高响应比优先调度算法C语言
时间: 2023-11-23 07:56:46 浏览: 75
以下是高响应比优先调度算法的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct process {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int waiting_time; // 等待时间
int turnaround_time; // 周转时间
int response_ratio; // 响应比
};
int main() {
int n, i, j;
float avg_waiting_time = 0, avg_turnaround_time = 0;
printf("请输入进程数:");
scanf("%d", &n);
struct process p[n], temp;
for (i = 0; i < n; i++) {
printf("请输入第%d个进程的到达时间和执行时间:", i + 1);
scanf("%d%d", &p[i].arrival_time, &p[i].burst_time);
p[i].pid = i + 1;
p[i].waiting_time = p[i].turnaround_time = 0;
p[i].response_ratio = 0;
}
// 计算等待时间、周转时间和响应比
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (p[i].arrival_time > p[j].arrival_time) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
int current_time = 0, completed = 0;
while (completed != n) {
int max_response_ratio = -1, index = -1;
for (i = 0; i < n; i++) {
if (p[i].arrival_time <= current_time && p[i].response_ratio > max_response_ratio) {
max_response_ratio = p[i].response_ratio;
index = i;
}
}
if (index != -1) {
p[index].waiting_time = current_time - p[index].arrival_time;
p[index].turnaround_time = p[index].waiting_time + p[index].burst_time;
p[index].response_ratio = (float) p[index].turnaround_time / p[index].burst_time;
avg_waiting_time += p[index].waiting_time;
avg_turnaround_time += p[index].turnaround_time;
current_time += p[index].burst_time;
completed++;
} else {
current_time++;
}
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
printf("进程ID\t到达时间\t执行时间\t等待时间\t周转时间\t响应比\n");
for (i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%.2f\n", p[i].pid, p[i].arrival_time, p[i].burst_time, p[i].waiting_time, p[i].turnaround_time, p[i].response_ratio);
}
printf("平均等待时间:%.2f\n", avg_waiting_time);
printf("平均周转时间:%.2f\n", avg_turnaround_time);
return 0;
}
```
阅读全文