#include<stdio.h>
#include<malloc.h>
typedef struct process
{
int p_name;
int cpu_time,arrival_time,finish_time,turn_time;
int waiting_time,start_time,cpu_temp,flag;
}process;
int main()
{
int no,i,total_cpu_time=0,j,processes,next_proc,current,x;
float avg_turn_time=0,avg_waiting_time=0;
process obj[7];
process small;
int waiting_proc=0,minus;
printf("\nEnter no of processes:");
scanf("\n%d",&no);
//Accepts input from user
for(i=0;i<no;i++)
{
printf("\nEnter Process ID, Arrival Time and CPU time\n");
scanf("%d%d%d",&obj[i].p_name,&obj[i].arrival_time,&obj[i].cpu_time);
obj[i].cpu_temp=obj[i].cpu_time;
total_cpu_time=total_cpu_time+obj[i].cpu_time;
}
for(i=0;i<no;i++)
{
obj[i].flag=0;
}
//Sort according to CPU time
processes=1;
current=0;
next_proc=1;
small=obj[0];
i=1;
printf("\n\tRunning Time\tProcess No\n");
while(i<=total_cpu_time)
{
if(obj[current].cpu_temp == obj[current].cpu_time)
{
obj[current].start_time=i-1;
}
minus=i-1;
printf("\n\t%d--%d\t\tp%d",minus,i,current);
obj[current].cpu_temp=obj[current].cpu_temp - 1;
if(obj[current].cpu_temp==0 && obj[current].flag==0)
{
obj[current].flag=1;
obj[current].finish_time=i;
printf("\np%d terminates here...",obj[current].p_name);
printf("\nFinish Time=%d",obj[current].finish_time);
waiting_proc=waiting_proc-1;
}
if(obj[next_proc].arrival_time==i && next_proc!=no)
{
next_proc=next_proc+1;
processes=processes+1;
waiting_proc=waiting_proc+1;
}
small=obj[current];
for(x=0;x<processes;x++)
{
if((small.cpu_temp>obj[x].cpu_temp) && (obj[x].flag==0))
{
small=obj[x];
current=x;
}
if((small.cpu_temp<obj[x].cpu_temp) && (small.flag==1))
{
small=obj[x];
current=x;
}
}
/* if(waiting_proc==0 && processes==no)
{
for(x=0;x<processes;x++)
{
if(obj[x].flag==0)
{
small=obj[x];
current=x;
}
}
}
*/
i++;
}
//calculates time for each process
for(i=0;i<no;i++)
{
obj[i].turn_time=obj[i].finish_time-obj[i].arrival_time;
obj[i].waiting_time=obj[i].turn_time-obj[i].cpu_time;
avg_turn_time=avg_turn_time+obj[i].turn_time;
avg_waiting_time=avg_waiting_time+obj[i].waiting_time;
}
//Display all times
printf("\n=======================================================================================================");
printf("\nP_ID\t Arrival_Time\t CPU_time\t Start_Time\t Finish_Time\t Turn_Time\t Waiting_Time");
printf("\n=======================================================================================================");
for(i=0;i<no;i++)
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d",obj[i].p_name,obj[i].arrival_time,obj[i].cpu_time,obj[i].start_time,obj[i].finish_time,obj[i].turn_time,obj[i].waiting_time);
}
printf("\n");
avg_turn_time=avg_turn_time/no;
avg_waiting_time=avg_waiting_time/no;
printf("\nAverage Turnaround Time=%f",avg_turn_time);
printf("\nAverage Waiting Time=%f",avg_waiting_time);
printf("\n");
return 0;
}
No comments:
Post a Comment