Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

CO-204 OS Lab S2 G3

Experiment 3
Name- Dhruv Gupta
Roll No- 2K21/EP/33

LJF - Longest Job First


Table
Process Id Arrival Time Burst Time Completion Turn around Waiting Time
Time time

P1 3 4 7 4 0

P2 5 3 13 8 5

P3 0 2 2 2 0

P4 5 1 14 9 8

P5 4 3 10 6 3

P3 Idle P1 P5 P2 P4
0 2 3 7 10 13 14

Average TAT = 5.8

Average WT = 3.2
Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Process {
public:
int id;
int at;
int bt;
int ct;
int tat;
int wt;
};
bool compareat(const Process& p1, const Process& p2) {
return p1.at < p2.at;
}
bool comparebt(const Process& p1, const Process& p2) {
// Compare based on burst time (in descending order)
return p1.bt > p2.bt;
}
void ljfScheduling(vector<Process>& p) {
// Sort processes based on arrival time
sort(p.begin(), p.end(), compareat);
int n = p.size();
vector<bool> completed(n, false);
int currentT = 0;
int done = 0;
while (done < n) {
int index = -1;
int maxBurst = -1;
// Find the longest job available at current time
for (int i = 0; i < n; ++i) {
if (!completed[i] && p[i].at <= currentT && p[i].bt > maxBurst) {
index = i;
maxBurst = p[i].bt;
}
}
// If no suitable process is found, move to the next arrival time
if (index == -1) {
currentT++;
}
else {
// Execute the longest job
p[index].ct = currentT + p[index].bt;
p[index].tat = p[index].ct - p[index].at;
p[index].wt = p[index].tat - p[index].bt;
done++;
currentT = p[index].ct;
completed[index] = true;
}
}
}
int main() {
int n;
cout << "Enter the number of processes: ";
cin >> n;
vector<Process> p(n);
for (int i = 0; i < n; i++) {
cout << "Enter the arrival time and burst time of process " << i + 1 << ": ";
cin >> p[i].at >> p[i].bt;
p[i].id = i + 1;
}
ljfScheduling(p);
sort(p.begin(), p.end(), [](const Process& p1, const Process& p2) { return p1.id <
p2.id; });
cout << "PID\tAT\tBT\tCT\tTAT\tWT\n";
for (int i = 0; i < n; i++) {
cout << p[i].id << "\t" << p[i].at << "\t" << p[i].bt << "\t" << p[i].ct << "\t" << p[i].tat
<< "\t" << p[i].wt << endl;
}
float avgTAT = 0, avgWT = 0;
for (int i = 0; i < n; i++) {
avgTAT += p[i].tat;
avgWT += p[i].wt;
}
avgTAT /= n;
avgWT /= n;
cout << "Average Turnaround Time: " << avgTAT << endl;
cout << "Average Waiting Time: " << avgWT << endl;
return 0;
}
Output

You might also like