-
Notifications
You must be signed in to change notification settings - Fork 0
/
(OS)Implementation of FCFS.cpp
82 lines (65 loc) · 2.3 KB
/
(OS)Implementation of FCFS.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Process {
int pid; // Process ID
int arrival; // Arrival time
int burst; // Burst time
};
void findWaitingTime(vector<Process>& processes, vector<int>& wt) {
wt[0] = 0; // Waiting time for the first process is 0
// Calculate waiting time for each process
for (int i = 1; i < processes.size(); i++) {
wt[i] = processes[i - 1].burst + wt[i - 1];
}
}
void findTurnAroundTime(vector<Process>& processes, vector<int>& wt, vector<int>& tat) {
// Calculate turnaround time by adding burst time and waiting time
for (int i = 0; i < processes.size(); i++) {
tat[i] = processes[i].burst + wt[i];
}
}
void findAverageTime(vector<Process>& processes) {
int n = processes.size();
vector<int> wt(n); // Vector to store waiting times
vector<int> tat(n); // Vector to store turnaround times
int total_wt = 0, total_tat = 0;
// Calculate waiting time of all processes
findWaitingTime(processes, wt);
// Calculate turnaround time of all processes
findTurnAroundTime(processes, wt, tat);
// Calculate total waiting time and total turnaround time
for (int i = 0; i < n; i++) {
total_wt += wt[i];
total_tat += tat[i];
}
// Calculate average waiting time and average turnaround time
float average_wt = (float)total_wt / n;
float average_tat = (float)total_tat / n;
// Display results
cout << "Processes Arrival Time Burst Time Waiting Time Turn-Around Time\n";
for (int i = 0; i < n; i++) {
cout << " " << processes[i].pid << "\t\t" << processes[i].arrival << "\t\t"
<< processes[i].burst << "\t\t" << wt[i] << "\t\t" << tat[i] << endl;
}
cout << "\nAverage waiting time: " << average_wt << endl;
cout << "Average turnaround time: " << average_tat << endl;
}
int main() {
// Example processes
vector<Process> processes = {
{1, 0, 5},
{2, 2, 3},
{3, 4, 7},
{4, 6, 2},
{5, 8, 4}
};
// Sort processes by arrival time
sort(processes.begin(), processes.end(), [](Process a, Process b) {
return a.arrival < b.arrival;
});
// Calculate average time
findAverageTime(processes);
return 0;
}