用C语言写一个短作业优先调度算法程序
时间: 2023-10-16 14:10:02 浏览: 130
好的,我可以帮您用C语言编写一个短作业优先调度算法程序。以下是代码:
```
#include<stdio.h>
struct process{
char pid[5];
int at, bt, ct, tat, wt;
int completed;
float ntt;
}p[10], temp;
int n;
void sortByArrival(){
int i, j;
for(i=0; i<n-1; i++){
for(j=i+1; j<n; j++){
if(p[i].at > p[j].at){
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
void main(){
int i, j, t, sum_bt=0;
char c;
float avgwt=0, avgtat=0, avgntt=0;
printf("Enter the no of processes: ");
scanf("%d", &n);
for(i=0, c='A'; i<n; i++, c++){
p[i].pid[0] = c;
printf("\nEnter the arrival time and burst time of process %c: ", p[i].pid[0]);
scanf("%d%d", &p[i].at, &p[i].bt);
p[i].completed = 0;
sum_bt += p[i].bt;
}
sortByArrival();
printf("\nProcess\tArrival Time\tBurst Time\tCompletion Time\tTurn-Around Time\tWaiting Time\t Normalized TAT");
for(t = p[0].at; t < sum_bt;){
float hrr = -9999;
for(i=0; i<n; i++){
if(p[i].at <= t && !p[i].completed){
float temp = (p[i].bt + (t - p[i].at)) / p[i].bt;
if(hrr < temp){
hrr = temp;
j = i;
}
}
}
p[j].ct = t + p[j].bt;
p[j].tat = p[j].ct - p[j].at;
p[j].wt = p[j].tat - p[j].bt;
p[j].ntt = ((float)p[j].tat / p[j].bt);
avgwt += p[j].wt;
avgtat += p[j].tat;
avgntt += p[j].ntt;
p[j].completed = 1;
t = p[j].ct;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t\t%d\t\t\t%d\t\t\t%f", p[j].pid[0], p[j].at, p[j].bt, p[j].ct, p[j].tat, p[j].wt, p[j].ntt);
}
printf("\nAverage waiting time: %f\n", avgwt/n);
printf("Average turn-around time: %f\n", avgtat/n);
printf("Average normalized TAT: %f\n", avgntt/n);
}
```
这是一个简单的短作业优先调度算法程序,它会根据进程的到达时间和运行时间,按照优先级将进程调度到CPU中。程序会输出每个进程的完成时间、周转时间、等待时间和标准化周转时间。最后,程序会计算平均等待时间、平均周转时间和平均标准化周转时间,并将它们输出到屏幕上。
阅读全文