SJF and SRTF scheduling programs with Gantt charts and captured output
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5v46dt7TVsHZxtoYC
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
// Shortest Remaining Time First (SRTF) - PREEMPTIVE SJF, simulated one time unit at a time.
|
||||
// At every tick, run the arrived process with the least remaining time. A newly arrived
|
||||
// process with a smaller remaining time preempts the running one.
|
||||
#include <climits>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
struct Process { int pid, at, bt, rem, ct = 0, tat = 0, wt = 0; };
|
||||
struct Slice { int pid, start, end; }; // pid = 0 means idle
|
||||
|
||||
int main() {
|
||||
int n;
|
||||
cin >> n;
|
||||
vector<Process> p(n);
|
||||
for (int i = 0; i < n; i++) { p[i].pid = i + 1; cin >> p[i].at >> p[i].bt; p[i].rem = p[i].bt; }
|
||||
|
||||
vector<Slice> gantt;
|
||||
int time = 0, finished = 0;
|
||||
while (finished < n) {
|
||||
int pick = -1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (p[i].rem == 0 || p[i].at > time) continue;
|
||||
if (pick == -1 || p[i].rem < p[pick].rem ||
|
||||
(p[i].rem == p[pick].rem && p[i].at < p[pick].at)) pick = i;
|
||||
}
|
||||
int pid = (pick == -1) ? 0 : p[pick].pid;
|
||||
if (!gantt.empty() && gantt.back().pid == pid) gantt.back().end = time + 1; // extend slice
|
||||
else gantt.push_back({pid, time, time + 1});
|
||||
if (pick != -1 && --p[pick].rem == 0) {
|
||||
p[pick].ct = time + 1;
|
||||
p[pick].tat = p[pick].ct - p[pick].at;
|
||||
p[pick].wt = p[pick].tat - p[pick].bt;
|
||||
finished++;
|
||||
}
|
||||
time++;
|
||||
}
|
||||
|
||||
cout << "Preemptive SJF (SRTF)\n\n";
|
||||
cout << "PID\tAT\tBT\tCT\tTAT\tWT\n";
|
||||
double sw = 0, st = 0;
|
||||
for (auto& q : p) {
|
||||
cout << "P" << q.pid << "\t" << q.at << "\t" << q.bt << "\t" << q.ct << "\t" << q.tat << "\t" << q.wt << "\n";
|
||||
sw += q.wt; st += q.tat;
|
||||
}
|
||||
cout << fixed << setprecision(2);
|
||||
cout << "\nAverage waiting time : " << sw / n << "\n";
|
||||
cout << "Average turnaround time : " << st / n << "\n\nGantt chart:\n";
|
||||
string top, nums;
|
||||
auto putNum = [&](int v) { nums += to_string(v); };
|
||||
for (auto& s : gantt) {
|
||||
string label = (s.pid ? "P" + to_string(s.pid) : string("idle"));
|
||||
if (nums.size() < top.size()) nums += string(top.size() - nums.size(), ' ');
|
||||
putNum(s.start);
|
||||
top += "| " + label + " ";
|
||||
}
|
||||
top += "|";
|
||||
if (nums.size() < top.size() - 1) nums += string(top.size() - 1 - nums.size(), ' ');
|
||||
putNum(gantt.back().end);
|
||||
cout << top << "\n" << nums << "\n";
|
||||
}
|
||||
Reference in New Issue
Block a user