编写C语言程序,实现高响应比优先调度算法, 要求输入提交时刻及运行时间,输出调度顺序。
时间: 2023-06-27 07:04:00 浏览: 91
以下是一个简单的高响应比优先调度算法的C语言实现:
```c
#include <stdio.h>
#define MAX_PROCESSES 10
typedef struct {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int priority; // 优先级
int waiting_time; // 等待时间
int turnaround_time; // 周转时间
float response_ratio; // 高响应比
} Process;
int main() {
Process processes[MAX_PROCESSES];
int n, i, j, total_waiting_time = 0, total_turnaround_time = 0;
float avg_waiting_time, avg_turnaround_time;
// 输入进程数
printf("Enter the number of processes: ");
scanf("%d", &n);
// 输入每个进程的信息
for (i = 0; i < n; i++) {
printf("Process %d\n", i + 1);
processes[i].pid = i + 1;
printf("Arrival time: ");
scanf("%d", &processes[i].arrival_time);
printf("Burst time: ");
scanf("%d", &processes[i].burst_time);
printf("Priority: ");
scanf("%d", &processes[i].priority);
processes[i].response_ratio = 0; // 初始化高响应比为0
}
// 计算每个进程的等待时间、周转时间和高响应比
for (i = 0; i < n; i++) {
// 计算等待时间
processes[i].waiting_time = 0;
for (j = 0; j < i; j++) {
processes[i].waiting_time += processes[j].burst_time;
}
processes[i].waiting_time -= processes[i].arrival_time;
if (processes[i].waiting_time < 0) {
processes[i].waiting_time = 0;
}
// 计算周转时间
processes[i].turnaround_time = processes[i].waiting_time + processes[i].burst_time;
// 计算高响应比
processes[i].response_ratio = (float) (processes[i].waiting_time + processes[i].burst_time) / processes[i].burst_time;
}
// 按高响应比排序
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (processes[i].response_ratio < processes[j].response_ratio) {
Process temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
// 输出调度顺序
printf("Process schedule: ");
for (i = 0; i < n; i++) {
printf("P%d ", processes[i].pid);
}
printf("\n");
// 计算平均等待时间和平均周转时间
for (i = 0; i < n; i++) {
total_waiting_time += processes[i].waiting_time;
total_turnaround_time += processes[i].turnaround_time;
}
avg_waiting_time = (float) total_waiting_time / n;
avg_turnaround_time = (float) total_turnaround_time / n;
// 输出平均等待时间和平均周转时间
printf("Average waiting time: %.2f\n", avg_waiting_time);
printf("Average turnaround time: %.2f\n", avg_turnaround_time);
return 0;
}
```
这个程序先输入进程数,然后依次输入每个进程的到达时间、执行时间和优先级。接着,它计算每个进程的等待时间、周转时间和高响应比,并按照高响应比排序。最后输出调度顺序和平均等待时间、平均周转时间。
阅读全文