3
1
SystemsProgrammingAndOperat.../Codes/Group B/Assignment - 5/SJF (Preemptive).cpp

98 lines
2.9 KiB
C++
Executable File

#include<iostream>
#include<limits.h> // for INT_MAX
using namespace std;
struct sjf{
int burst, arrival, id, completion, waiting, turnaround, response;
bool active;
};
sjf meh[30];
class lesgo{
public:
int n;
void sjfIn(){
cout<<"\nEnter number of processes: ";
cin>>n;
for(int i = 1; i <= n; i++){
cout<<"\nEnter arrival time of P"<<i<<": ";
cin>>meh[i].arrival;
cout<<"\nEnter burst time of P"<<i<<": ";
cin>>meh[i].burst;
meh[i].id = i;
meh[i].active = false;
}
cout<<"\n | Arrival | Burst\n";
for(int j = 1; j <= n; j++) {
cout<<"P"<<j<<"| "<<meh[j].arrival<<" | "<<meh[j].burst<<"\n";
}
}
void sjfProcess(){
int k = 0;
int completed = 0;
cout<<"\nSequence of processes is: ";
while(completed < n){
int burst1 = INT_MAX; // Initialize to the maximum possible value
int iddd = -1;
for(int i = 1; i <= n; i++){
if(meh[i].arrival <= k && meh[i].burst > 0){
if(meh[i].burst < burst1){
burst1 = meh[i].burst;
iddd = i;
}
}
}
if(iddd != -1){
// Mark the process as active
if(!meh[iddd].active) {
meh[iddd].response = k - meh[iddd].arrival;
meh[iddd].active = true;
}
cout<<"P"<<iddd<<" ";
meh[iddd].burst--;
k++;
if(meh[iddd].burst == 0){
meh[iddd].completion = k;
meh[iddd].turnaround = meh[iddd].completion - meh[iddd].arrival;
meh[iddd].waiting = meh[iddd].turnaround - (meh[iddd].response + 1); // +1 for the final unit burst time
completed++;
}
} else{
k++;
}
}
}
void displayMetrics(){
double totalWaiting = 0, totalTurnaround = 0, totalCompletion = 0;
cout<<"\n\n | Completion time | Waiting time | Turnaround time | Response time\n";
for(int j = 1; j <= n; j++) {
totalWaiting += meh[j].waiting;
totalTurnaround += meh[j].turnaround;
totalCompletion += meh[j].completion;
cout<<"P"<<j<<"| "<<meh[j].completion
<<" | "<<meh[j].waiting
<<" | "<<meh[j].turnaround
<<" | "<<meh[j].response<<"\n";
}
cout<<"\nAverage completion time: "<<totalCompletion/n;
cout<<"\nAverage waiting time: "<<totalWaiting/n;
cout<<"\nAverage turnaround time: "<<totalTurnaround/n;
}
};
int main(){
lesgo obj;
obj.sjfIn();
obj.sjfProcess();
obj.displayMetrics();
return 0;
}