高响应比优先调度算法c语言代码
时间: 2023-07-24 12:18:34 浏览: 51
以下是一个简单的高响应比优先调度算法的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESSES 10
struct process {
int pid; // 进程 ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int response_ratio; // 响应比
int completion_time; // 完成时间
int turnaround_time; // 周转时间
int waiting_time; // 等待时间
};
int compare(const void *a, const void *b) {
struct process *process_a = (struct process *) a;
struct process *process_b = (struct process *) b;
return process_b->response_ratio - process_a->response_ratio;
}
void calculate_waiting_time(struct process processes[], int n) {
int time = 0;
int i;
for (i = 0; i < n; i++) {
if (time < processes[i].arrival_time) {
time = processes[i].arrival_time;
}
processes[i].completion_time = time + processes[i].burst_time;
processes[i].turnaround_time = processes[i].completion_time - processes[i].arrival_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
time = processes[i].completion_time;
}
}
void print_table(struct process processes[], int n) {
int i;
int total_waiting_time = 0;
int total_turnaround_time = 0;
printf("PID\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time\n");
for (i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t\t%d\n", processes[i].pid, processes[i].arrival_time,
processes[i].burst_time, processes[i].completion_time, processes[i].turnaround_time,
processes[i].waiting_time);
total_waiting_time += processes[i].waiting_time;
total_turnaround_time += processes[i].turnaround_time;
}
printf("Average waiting time: %.2f\n", (float) total_waiting_time / n);
printf("Average turnaround time: %.2f\n", (float) total_turnaround_time / n);
}
int main() {
int n;
struct process processes[MAX_PROCESSES];
int i;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the arrival time and burst time for each process:\n");
for (i = 0; i < n; i++) {
processes[i].pid = i + 1;
printf("Process %d: ", processes[i].pid);
scanf("%d %d", &processes[i].arrival_time, &processes[i].burst_time);
processes[i].response_ratio = 1 + (processes[i].waiting_time / processes[i].burst_time);
}
qsort(processes, n, sizeof(struct process), compare);
calculate_waiting_time(processes, n);
print_table(processes, n);
return 0;
}
```
注意,这只是一个简单的示例代码,实际情况中可能需要根据具体的需求进行修改。
阅读全文