Let's simulate Shortest Job First (SJF) CPU Scheduling algorithm using C.

In this article, we are going to simulate SJF algorithm in the simplest possible method.

Here we are assuming that arrival time is 0 for all processes.

SJF is actually two types, pre-emptive and non-preemptive

Here we are doing the non-preemptive method.

**The logic used in this program is pretty simple. Steps are**

1. Read the number of processes from the input different arrays

2. Sort the entire table on the basis of Burst Time. (Don't forget to change PID values accordingly. Otherwise, there will be a PID and burst time mismatch if you only sort Burst time)

That's it. Then you can simply calculate the Average Waiting time and Average Turnaround time using the basic calculations.

// SJF Scheduling Simulated using C. Code by Nived Kannada #include<stdio.h> void main() { int n, bt[20], at[20],p[20],wt[20],tat[20],i,j , total=0, pos, temp; float avgwt=0, avgtat=0; //Reading number of processes from input. printf("Enter number of processes: "); scanf("%d",&n); //Reading all burst times of processes from input. Assuming Arrival time is 0 for all. printf("Enter burst time of each process: \n"); for(i=0;i<n;i++) { p[i]=i; printf("Burst Time of P[%d]: ",i); scanf("%d",&bt[i]); at[i]=0; //Assuming AT is zero for all. } //Sorting Burst Time in its Ascending Order for(i=0;i<n;i++) { pos = i; for(j=i+1;j<n;j++) { if(bt[j]<bt[pos]) { pos=j; } } temp=bt[i]; bt[i]=bt[pos]; bt[pos]=temp; //Also sorting corresponding PID values. temp=p[i]; p[i]=p[pos]; p[pos]=temp; } //After this sorting step, the array bt[] is in ascending order. So the first element in the bt[] array doesn't have to wait. Its wt is now 0 /* CALCULATING WAITING TIME */ wt[0]=0; //The current first Process doesnt have to wait, (after sorting) //Setting wt values for all other processes. for(i=1;i<n;i++) //wt of 0 is set as 0. So we start with index 1 of wt[]. { wt[i]=0; //initialize wt of i'th index as 0 for(j=0;j<i;j++) { wt[i] = wt[i] + bt[j]; // adding waiting times of previous processes and the current burst time. } } /* CALCULATING TURNAROUND TIME */ for(i=0;i<n;i++) { tat[i] = wt[i] + bt[i]; //Equation for TAT is TAT= WT+BT } //Displaying Table printf("\n\tPID\tAT\tBT\tWT\tTAT\n"); for(i=0;i<n;i++) { printf("\t%d\t%d\t%d\t%d\t%d\n",p[i],at[i],bt[i],wt[i],tat[i]); } //Calculating Average Waiting time and Average Turnaround Time for(i=0;i<n;i++) { avgwt = avgwt + wt[i]; avgtat = avgtat + tat[i]; } avgwt = avgwt/n; avgtat = avgtat/n; //Displaying Average WT and Average TAT printf("\nAverage WT = %f\n", avgwt); printf("\nAverage TAT = %f\n", avgtat); } //END OF PROGRAM

## No comments:

## Post a Comment