-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsjf_at1.cpp
111 lines (96 loc) · 3.09 KB
/
sjf_at1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include<iostream>
#include <algorithm>
#include<iomanip>
#include<climits>
using namespace std;
struct process_struct
{
int pid;
int at;
int bt;
int ct,wt,tat,rt,start_time;
}ps[100];
int main()
{
int n;
bool is_completed[100]={false},is_first_process=true;
int current_time = 0;
int completed = 0;;
cout<<"Enter total number of processes: ";
cin>>n;
int sum_tat=0,sum_wt=0,sum_rt=0,total_idle_time=0,prev=0,length_cycle;
float cpu_utilization;
int max_completion_time,min_arrival_time;
cout << fixed << setprecision(2);
for(int i=0;i<n;i++)
{
cout<<"\nEnter Process " <<i<< " Arrival Time: ";
cin >> ps[i].at;
ps[i].pid=i;
}
for(int i=0;i<n;i++)
{
cout<<"\nEnter Process " <<i<< " Burst Time: ";
cin >> ps[i].bt;
}
while(completed!=n)
{
//find process with min. burst time in ready queue at current time
int min_index = -1;
int minimum = INT_MAX;
for(int i = 0; i < n; i++) {
if(ps[i].at <= current_time && is_completed[i] == false) {
if(ps[i].bt < minimum) {
minimum = ps[i].bt;
min_index = i;
}
if(ps[i].bt== minimum) {
if(ps[i].at < ps[min_index].at) {
minimum= ps[i].bt;
min_index = i;
}
}
}
}
if(min_index==-1)
{
current_time++;
}
else
{
ps[min_index].start_time = current_time;
ps[min_index].ct = ps[min_index].start_time + ps[min_index].bt;
ps[min_index].tat = ps[min_index].ct - ps[min_index].at;
ps[min_index].wt = ps[min_index].tat - ps[min_index].bt;
ps[min_index].rt = ps[min_index].wt;
// ps[min_index].rt = ps[min_index].start_time - ps[min_index].at;
sum_tat +=ps[min_index].tat;
sum_wt += ps[min_index].wt;
sum_rt += ps[min_index].rt;
total_idle_time += (is_first_process==true) ? 0 : (ps[min_index].start_time - prev);
completed++;
is_completed[min_index]=true;
current_time = ps[min_index].ct;
prev= current_time;
is_first_process = false;
}
}
//Calculate Length of Process completion cycle
max_completion_time = INT_MIN;
min_arrival_time = INT_MAX;
for(int i=0;i<n;i++)
{
max_completion_time = max(max_completion_time,ps[i].ct);
min_arrival_time = min(min_arrival_time,ps[i].at);
}
length_cycle = max_completion_time - min_arrival_time;
//Output
cout<<"\nProcess No.\tAT\tCPU Burst Time\tCT\tTAT\tWT\n";
for(int i=0;i<n;i++)
cout<<i<<"\t\t"<<ps[i].at<<"\t"<<ps[i].bt<<"\t\t"<<ps[i].ct<<"\t"<<ps[i].tat<<"\t"<<ps[i].wt<<endl;
cout<<endl;
cpu_utilization = (float)(length_cycle - total_idle_time)/ length_cycle;
cout<<"\nAverage TurnAround time= "<< (float)sum_tat/n;
cout<<"\nAverage Waiting Time= "<<(float)sum_wt/n;
return 0;
}