Вычисление средних времен и отображение итоговых результатов
На этом последнем этапе мы вычислим среднее время ожидания и среднее время выполнения для всех процессов. Эти средние значения являются важными показателями для оценки эффективности алгоритма планирования.
Давайте модифицируем наш файл fcfs.cpp
, чтобы добавить эти вычисления и завершить нашу программу:
#include <iostream>
#include <iomanip> // For formatted output
using namespace std;
int main() {
cout << "FCFS Scheduling Algorithm Implementation" << endl;
cout << "----------------------------------------" << endl;
// Variables declaration
int n; // Number of processes
int burst_time[20]; // Array to store burst time of each process
int waiting_time[20]; // Array to store waiting time of each process
int turnaround_time[20]; // Array to store turnaround time of each process
int total_waiting_time = 0;
int total_turnaround_time = 0;
float avg_waiting_time = 0.0;
float avg_turnaround_time = 0.0;
// Get the number of processes from the user
cout << "\nEnter the number of processes (maximum 20): ";
cin >> n;
// Input validation
if (n <= 0 || n > 20) {
cout << "Invalid number of processes. Please enter a value between 1 and 20." << endl;
return 1;
}
// Get burst time for each process
cout << "\nEnter the Burst Time for each process:" << endl;
for (int i = 0; i < n; i++) {
cout << "Process P" << i + 1 << ": ";
cin >> burst_time[i];
// Input validation for burst time
if (burst_time[i] <= 0) {
cout << "Burst time must be a positive integer. Please restart the program." << endl;
return 1;
}
}
// Calculate waiting time for each process
waiting_time[0] = 0; // First process has 0 waiting time
for (int i = 1; i < n; i++) {
waiting_time[i] = 0;
// Add burst times of all previous processes
for (int j = 0; j < i; j++) {
waiting_time[i] += burst_time[j];
}
}
// Calculate turnaround time for each process and total times
cout << "\nProcess\tBurst Time\tWaiting Time\tTurnaround Time" << endl;
cout << "----------------------------------------------------" << endl;
for (int i = 0; i < n; i++) {
turnaround_time[i] = burst_time[i] + waiting_time[i];
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
cout << "P" << i + 1 << "\t" << burst_time[i] << "\t\t"
<< waiting_time[i] << "\t\t" << turnaround_time[i] << endl;
}
// Calculate average waiting time and average turnaround time
avg_waiting_time = (float)total_waiting_time / n;
avg_turnaround_time = (float)total_turnaround_time / n;
// Display the results with two decimal places
cout << fixed << setprecision(2);
cout << "\nAverage Waiting Time: " << avg_waiting_time << " time units" << endl;
cout << "Average Turnaround Time: " << avg_turnaround_time << " time units" << endl;
// Visual representation of the FCFS schedule (Gantt chart in text)
cout << "\nGantt Chart:" << endl;
cout << " ";
for (int i = 0; i < n; i++) {
for (int j = 0; j < burst_time[i]; j++) {
cout << "--";
}
}
cout << endl << "|";
for (int i = 0; i < n; i++) {
for (int j = 0; j < burst_time[i] - 1; j++) {
cout << " ";
}
cout << "P" << i + 1;
for (int j = 0; j < burst_time[i] - 1; j++) {
cout << " ";
}
cout << "|";
}
cout << endl << " ";
for (int i = 0; i < n; i++) {
for (int j = 0; j < burst_time[i]; j++) {
cout << "--";
}
}
cout << endl;
cout << "0";
int current_time = 0;
for (int i = 0; i < n; i++) {
current_time += burst_time[i];
for (int j = 0; j < burst_time[i] * 2 - 1; j++) {
cout << " ";
}
if (current_time < 10) cout << " ";
cout << current_time;
}
cout << endl;
return 0;
}
Разберем, что мы добавили:
- Две новые переменные:
avg_waiting_time
и avg_turnaround_time
для хранения средних времен.
- Вычисления средних времен:
- Среднее время ожидания = Общее время ожидания / Количество процессов
- Среднее время выполнения = Общее время выполнения / Количество процессов
- Отформатированный вывод для отображения средних времен с двумя знаками после запятой.
- Простая текстовая диаграмма Ганта для визуального представления расписания FCFS:
- Каждый процесс представлен своим идентификатором (P1, P2 и т.д.)
- Ширина каждого блока процесса пропорциональна его времени выполнения
- Метки времени показаны внизу
Скомпилируем и запустим нашу окончательную программу:
g++ fcfs.cpp -o fcfs
./fcfs
Попробуйте ввести те же данные, что и раньше:
3
5
9
4
Вы должны увидеть вывод, похожий на следующий:
FCFS Scheduling Algorithm Implementation
----------------------------------------
Enter the number of processes (maximum 20): 3
Enter the Burst Time for each process:
Process P1: 5
Process P2: 9
Process P3: 4
Process Burst Time Waiting Time Turnaround Time
----------------------------------------------------
P1 5 0 5
P2 9 5 14
P3 4 14 18
Average Waiting Time: 6.33 time units
Average Turnaround Time: 12.33 time units
Gantt Chart:
--------------------
| P1 | P2 | P3 |
--------------------
0 5 14 18
Рассмотрим результаты:
- Среднее время ожидания: (0 + 5 + 14) / 3 = 6.33 единицы времени
- Среднее время выполнения: (5 + 14 + 18) / 3 = 12.33 единицы времени
Диаграмма Ганта визуально показывает, как процессы запланированы во времени:
- P1 выполняется с времени 0 до 5
- P2 выполняется с времени 5 до 14
- P3 выполняется с времени 14 до 18
Это завершает нашу реализацию алгоритма планирования FCFS. Вы можете поэкспериментировать с разными количествами процессов и временами выполнения, чтобы увидеть, как это влияет на среднее время ожидания и время выполнения.