短进程优先算法c语言实现
时间: 2023-07-27 19:07:04 浏览: 157
短进程优先算法(Shortest Job First,SJF)是一种调度算法,它根据进程的执行时间来进行排序,执行时间短的进程先执行。下面是一个简单的 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESS 100
typedef struct process {
int pid;
int burst_time;
int waiting_time;
int turnaround_time;
} Process;
void swap(Process *a, Process *b) {
Process temp = *a;
*a = *b;
*b = temp;
}
void sort(Process processes[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (processes[i].burst_time > processes[j].burst_time) {
swap(&processes[i], &processes[j]);
}
}
}
}
void calculate_times(Process processes[], int n) {
int total_waiting_time = 0;
int total_turnaround_time = 0;
int completion_time[MAX_PROCESS];
// 初始化完成时间数组
for (int i = 0; i < n; i++) {
completion_time[i] = 0;
}
completion_time[0] = processes[0].burst_time;
for (int i = 1; i < n; i++) {
completion_time[i] = completion_time[i - 1] + processes[i].burst_time;
}
for (int i = 0; i < n; i++) {
processes[i].turnaround_time = completion_time[i];
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
total_waiting_time += processes[i].waiting_time;
total_turnaround_time += processes[i].turnaround_time;
}
printf("Process ID\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].burst_time, processes[i].waiting_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;
Process processes[MAX_PROCESS];
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++) {
processes[i].pid = i + 1;
printf("Process %d: ", processes[i].pid);
scanf("%d", &processes[i].burst_time);
}
sort(processes, n);
calculate_times(processes, n);
return 0;
}
```
在上面的代码中,我们使用了结构体来表示每个进程,其中包括 pid(进程编号)、burst_time(执行时间)、waiting_time(等待时间)和 turnaround_time(周转时间)。sort 函数根据进程的执行时间对它们进行排序。calculate_times 函数计算每个进程的等待时间和周转时间,并打印出来,最后输出平均等待时间和平均周转时间。主函数中,我们从用户输入中读取进程的执行时间,并调用 sort 和 calculate_times 函数。
注意,这个实现中没有考虑进程的到达时间,因为 SJF 算法是非抢占式的,即一旦进程开始执行,它就会一直执行到完成。如果要考虑进程的到达时间,可以使用 SJF 的改进版本,即短作业优先算法(Shortest Job First with Arrival Time,SJF-AT)。
阅读全文