dff

 avatar
unknown
c_cpp
5 months ago
2.6 kB
5
Indexable
#include <iostream>
#include <vector>
#include <iomanip> // For std::setw
using namespace std;

void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum, vector<int>& ganttChart) {
    int rem_bt[n]; // Remaining burst time for each process
    for (int i = 0; i < n; i++)
        rem_bt[i] = bt[i];

    int t = 0; // Current time
    while (true) {
        bool done = true;
        for (int i = 0; i < n; i++) {
            if (rem_bt[i] > 0) {
                done = false; // There is a pending process
                ganttChart.push_back(processes[i]); // Add process to Gantt chart
                if (rem_bt[i] > quantum) {
                    t += quantum;
                    rem_bt[i] -= quantum;
                } else { // If remaining time is less than or equal to quantum
                    t += rem_bt[i];
                    wt[i] = t - bt[i];
                    rem_bt[i] = 0; // Process is completed
                }
            }
        }
        if (done)
            break;
    }
}

void findTurnaroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
    for (int i = 0; i < n; i++)
        tat[i] = bt[i] + wt[i];
}

void findAvgTime(int processes[], int n, int bt[], int quantum) {
    int wt[n], tat[n], total_wt = 0, total_tat = 0;
    vector<int> ganttChart;

    findWaitingTime(processes, n, bt, wt, quantum, ganttChart);
    findTurnaroundTime(processes, n, bt, wt, tat);

    cout << "PN\tBT\tWT\tTAT\n";
    for (int i = 0; i < n; i++) {
        total_wt += wt[i];
        total_tat += tat[i];
        cout <<processes[i] << "\t" << bt[i] << "\t" << wt[i] << "\t" << tat[i] << endl;
    }

    cout << "Average waiting time: " << (float)total_wt / n << endl;
    cout << "Average turnaround time: " << (float)total_tat / n << endl;

    // Display Gantt Chart
    cout << "\nGantt Chart:\n";
    
    // Print time slots
    cout << "Time: ";
    for (size_t i = 0; i < ganttChart.size(); ++i) {
        cout << setw(4) << (i == 0 ? 0 : (i * quantum)) << " ";
    }
    cout << setw(4) << (ganttChart.size() * quantum) << endl; // Final time

    // Print process IDs in Gantt chart
    cout << "Processes: ";
    for (int proc : ganttChart) {
        cout << "P" << proc + 1 << "   "; // Display process IDs starting from P1
    }
    cout << endl;
}

int main() {
    // Predefined example usage:
    int processes[] = {1, 2 , 3 }; // Process IDs
    int burst_time[] = {10, 5, 8}; // Burst times
    int quantum = 2; // Time quantum
    int n = sizeof(processes) / sizeof(processes[0]);

    findAvgTime(processes, n, burst_time, quantum);
    
    return 0;
}
Editor is loading...
Leave a Comment