Non Preemptive SJF scheduling algorithm in C
Non Preemptive SJF scheduling algorithm in C.
This is a working code with output.
If you want the explanation for this code, you can view: this video YouTube Link
#include <stdio.h>
typedef struct process {
int id , at , bt ,rt, ct , tat , wt;
} process;
void display(process proc[] , int n) {
int i;
printf("\n\nP AT BT CT TAT WT\n");
for(i = 0; i < n; i++) {
printf("P%d %2d %2d %2d %2d %2d\n" ,
proc[i].id,
proc[i].at,
proc[i].bt,
proc[i].ct,
proc[i].tat,
proc[i].wt
);
}
}
void nonsjf(process proc[] , int n) {
int p = n;
int i , j;
int time = 0;
while(p > 0) {
int min = -1;
for(i = 0; i < n; i++) {
if(proc[i].at <= time && proc[i].rt > 0) {
if(min == -1 || proc[i].rt < proc[min].rt) {
min = i;
}
}
}
if(min == -1) time++;
else {
time += proc[min].rt;
proc[min].ct = time;
proc[min].rt = 0;
p--;
}
}
int ttat = 0;
int twt = 0;
for(i = 0; i < n; i++) {
proc[i].tat = proc[i].ct - proc[i].at;
proc[i].wt = proc[i].tat - proc[i].bt;
ttat += proc[i].tat;
twt += proc[i].wt;
}
display(proc , n);
printf("\nAvg TAT %0.2f\nAvg WT %0.2f\n" , (ttat * 1.0) / n , (twt * 1.0) / n);
}
int main() {
int n;
printf("Enter number of process: ");
scanf(" %d" , &n);
process proc[n];
int i;
for(i = 0; i < n; i++) {
proc[i].id = i+1;
printf("\nFor P%d\n", i+1);
printf("Enter AT: ");
scanf(" %d" , &proc[i].at);
printf("Enter BT: ");
scanf(" %d" , &proc[i].bt);
proc[i].rt = proc[i].bt;
proc[i].ct = proc[i].tat = proc[i].wt = 0;
}
nonsjf(proc , n);
return 0;
}
// 4 0 3 0 2 1 1 2 5
Comments
Post a Comment