用c语言编写程序,编写并调试一个模拟的进程调度程序,采用 “短进程优先”调度算法对多个进程进行调度。计算平均周转时间和平均带权周转时间。
时间: 2024-01-22 17:17:47 浏览: 63
下面是一个简单的模拟进程调度程序,采用短进程优先调度算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESSES 10
typedef struct {
int pid;
int arrival_time;
int burst_time;
int completion_time;
int turnaround_time;
int waiting_time;
float normalized_turnaround_time;
} Process;
void calculate(Process processes[], int n);
void print_results(Process processes[], int n);
int main() {
int n, i;
Process processes[MAX_PROCESSES];
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);
}
calculate(processes, n);
print_results(processes, n);
return 0;
}
void calculate(Process processes[], int n) {
int i, j, min_index, time = 0;
float avg_turnaround_time = 0, avg_normalized_turnaround_time = 0;
for (i = 0; i < n; i++) {
min_index = i;
for (j = i + 1; j < n; j++) {
if (processes[j].burst_time < processes[min_index].burst_time) {
min_index = j;
}
}
if (i != min_index) {
Process temp = processes[i];
processes[i] = processes[min_index];
processes[min_index] = temp;
}
}
for (i = 0; i < n; i++) {
time += processes[i].burst_time;
processes[i].completion_time = 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;
processes[i].normalized_turnaround_time = (float) processes[i].turnaround_time / processes[i].burst_time;
avg_turnaround_time += processes[i].turnaround_time;
avg_normalized_turnaround_time += processes[i].normalized_turnaround_time;
}
avg_turnaround_time /= n;
avg_normalized_turnaround_time /= n;
}
void print_results(Process processes[], int n) {
int i;
printf("\nProcess\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time\tNormalized Turnaround 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\t\t%.2f\n", processes[i].pid, processes[i].arrival_time,
processes[i].burst_time, processes[i].completion_time, processes[i].turnaround_time,
processes[i].waiting_time, processes[i].normalized_turnaround_time);
}
printf("\nAverage Turnaround Time: %.2f\n", avg_turnaround_time);
printf("Average Normalized Turnaround Time: %.2f\n", avg_normalized_turnaround_time);
}
```
代码中采用了一个简单的选择排序来将进程按照短作业优先的顺序排列,然后计算每个进程的完成时间、周转时间、等待时间和带权周转时间,并计算平均周转时间和平均带权周转时间。
注意,这里假设所有进程都在开始时同时到达,并且没有抢占调度。如果需要考虑更复杂的情况,如进程在运行时被抢占,可以进行修改。
阅读全文