高响应比优先调度算法C语言实现
时间: 2023-06-23 12:09:57 浏览: 179
高响应比优先调度算法是一种基于进程剩余服务时间和等待时间的调度算法,它可以保证短作业优先和响应时间的平衡。
下面是一个简单的 C 语言实现:
```c
#include <stdio.h>
#define MAX_PROCESS 10
struct Process {
int pid;
int burst_time;
int arrival_time;
int wait_time;
int turnaround_time;
int remaining_time;
float response_ratio;
};
int main() {
struct Process p[MAX_PROCESS];
int n, i, j, t, sum_wait_time = 0, sum_turnaround_time = 0;
float avg_wait_time, avg_turnaround_time;
printf("Enter the number of processes: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter the burst time and arrival time of process %d: ", i + 1);
scanf("%d %d", &p[i].burst_time, &p[i].arrival_time);
p[i].pid = i + 1;
p[i].remaining_time = p[i].burst_time;
}
// Sort processes by arrival time
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (p[i].arrival_time > p[j].arrival_time) {
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
// Calculate response ratio and sort processes by response ratio
for (i = 0; i < n; i++) {
t = 0;
for (j = 0; j < i; j++) {
t += p[j].burst_time;
}
p[i].wait_time = t - p[i].arrival_time;
p[i].response_ratio = (float) (p[i].wait_time + p[i].burst_time) / p[i].burst_time;
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (p[i].response_ratio < p[j].response_ratio) {
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
// Calculate wait time, turnaround time and remaining time for each process
for (i = 0; i < n; i++) {
t = 0;
for (j = 0; j < i; j++) {
t += p[j].burst_time;
}
p[i].wait_time = t - p[i].arrival_time;
p[i].turnaround_time = p[i].burst_time + p[i].wait_time;
sum_wait_time += p[i].wait_time;
sum_turnaround_time += p[i].turnaround_time;
p[i].remaining_time = 0;
}
// Calculate average wait time and turnaround time
avg_wait_time = (float) sum_wait_time / n;
avg_turnaround_time = (float) sum_turnaround_time / n;
// Print the result
printf("\nProcess\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].burst_time, p[i].arrival_time, p[i].wait_time,
p[i].turnaround_time);
}
printf("\nAverage Waiting Time: %.2f", avg_wait_time);
printf("\nAverage Turnaround Time: %.2f", avg_turnaround_time);
return 0;
}
```
在这个实现中,我们首先输入进程的数量和每个进程的到达时间和服务时间。然后,我们按照到达时间对进程进行排序,并计算每个进程的等待时间和响应比。最后,我们按照响应比对进程进行排序,并计算每个进程的等待时间和周转时间。
最后,我们输出每个进程的详细信息,以及平均等待时间和平均周转时间。
阅读全文