短进程优先调度算法c语言代码
时间: 2023-07-29 13:14:46 浏览: 129
短进程优先调度算法
3星 · 编辑精心推荐
以下是短进程优先调度算法的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct process {
int pid; // 进程ID
int arrival_time; // 到达时间
int burst_time; // 执行时间
int waiting_time; // 等待时间
int turnaround_time; // 周转时间
int status; // 进程状态,0表示未执行,1表示执行完毕
};
int main() {
int n, i, j, smallest;
float avg_waiting_time = 0, avg_turnaround_time = 0;
printf("Enter the number of processes: ");
scanf("%d", &n);
struct process p[n], temp;
for(i = 0; i < n; i++) {
printf("Enter the arrival time and burst time of process %d: ", i+1);
scanf("%d %d", &p[i].arrival_time, &p[i].burst_time);
p[i].pid = i+1;
p[i].status = 0;
}
// 对进程按照到达时间进行排序
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(p[j].arrival_time > p[j+1].arrival_time) {
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
// 执行进程
int current_time = 0, completed = 0, flag = 0;
while(completed != n) {
smallest = n-1;
for(i = 0; i < n; i++) {
if(p[i].arrival_time <= current_time && p[i].status == 0 && p[i].burst_time < p[smallest].burst_time) {
smallest = i;
flag = 1;
}
}
if(flag == 0) {
current_time++;
continue;
}
p[smallest].waiting_time = current_time - p[smallest].arrival_time;
p[smallest].turnaround_time = p[smallest].burst_time + p[smallest].waiting_time;
current_time += p[smallest].burst_time;
p[smallest].status = 1;
completed++;
avg_waiting_time += p[smallest].waiting_time;
avg_turnaround_time += p[smallest].turnaround_time;
flag = 0;
}
// 输出结果
printf("PID\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time\n");
for(i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].arrival_time, p[i].burst_time, p[i].waiting_time, p[i].turnaround_time);
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
printf("Average Waiting Time: %.2f\n", avg_waiting_time);
printf("Average Turnaround Time: %.2f\n", avg_turnaround_time);
return 0;
}
```
在该实现中,首先通过结构体定义了进程的属性,然后通过用户输入初始化了进程数组。接着对进程按照到达时间进行排序,然后循环执行进程,选择剩余执行时间最短的进程进行执行。在执行完毕后计算每个进程的等待时间和周转时间,并输出结果。最后计算平均等待时间和平均周转时间输出。
阅读全文