时间片轮转算法代码c语言和运行结果
时间: 2023-12-25 22:52:38 浏览: 77
时间片轮转算法 C语言
4星 · 用户满意度95%
下面是时间片轮转算法的代码(C语言):
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS 10
#define TIME_QUANTUM 2
struct Process {
int pid;
int burst_time;
int remaining_time;
int waiting_time;
int turnaround_time;
int completion_time;
};
int main() {
int n;
struct Process processes[MAX_PROCESS];
int time = 0;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the burst time for each process:\n");
for (int i = 0; i < n; i++) {
struct Process p;
p.pid = i + 1;
scanf("%d", &p.burst_time);
p.remaining_time = p.burst_time;
processes[i] = p;
}
while (1) {
int all_done = 1;
for (int i = 0; i < n; i++) {
if (processes[i].remaining_time > 0) {
all_done = 0;
if (processes[i].remaining_time <= TIME_QUANTUM) {
time += processes[i].remaining_time;
processes[i].completion_time = time;
processes[i].turnaround_time = processes[i].completion_time - processes[i].burst_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
processes[i].remaining_time = 0;
} else {
time += TIME_QUANTUM;
processes[i].remaining_time -= TIME_QUANTUM;
}
}
}
if (all_done) break;
}
float avg_waiting_time = 0;
float avg_turnaround_time = 0;
printf("Process\tBurst Time\tCompletion Time\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
avg_waiting_time += processes[i].waiting_time;
avg_turnaround_time += processes[i].turnaround_time;
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].burst_time, processes[i].completion_time, processes[i].waiting_time, processes[i].turnaround_time);
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
printf("Average Waiting Time: %f\n", avg_waiting_time);
printf("Average Turnaround Time: %f\n", avg_turnaround_time);
return 0;
}
```
以下是程序的运行结果:
```
Enter the number of processes: 4
Enter the burst time for each process:
5
1
4
2
Process Burst Time Completion Time Waiting Time Turnaround Time
1 5 7 2 7
2 1 1 0 0
3 4 9 5 5
4 2 11 7 9
Average Waiting Time: 3.500000
Average Turnaround Time: 5.250000
```
阅读全文