c++

c++怎么实现fcfs算法

小亿
119
2023-12-01 09:58:41
栏目: 编程语言

首先,FCFS(First-Come, First-Served)是一种先来先服务的调度算法,按照任务到达的顺序依次执行。

以下是一个简单的C++实现FCFS调度算法的示例:

#include <iostream>
#include <vector>

struct Process {
    int arrivalTime;
    int burstTime;
};

void calculateWaitingTime(std::vector<Process>& processes, std::vector<int>& waitingTimes) {
    int n = processes.size();
    waitingTimes[0] = 0; // 第一个进程的等待时间为0

    for (int i = 1; i < n; i++) {
        waitingTimes[i] = processes[i - 1].burstTime + waitingTimes[i - 1];
    }
}

void calculateTurnaroundTime(std::vector<Process>& processes, std::vector<int>& waitingTimes, std::vector<int>& turnaroundTimes) {
    int n = processes.size();

    for (int i = 0; i < n; i++) {
        turnaroundTimes[i] = processes[i].burstTime + waitingTimes[i];
    }
}

void calculateAverageTime(std::vector<Process>& processes) {
    int n = processes.size();
    std::vector<int> waitingTimes(n);
    std::vector<int> turnaroundTimes(n);

    calculateWaitingTime(processes, waitingTimes);
    calculateTurnaroundTime(processes, waitingTimes, turnaroundTimes);

    int totalWaitingTime = 0;
    int totalTurnaroundTime = 0;

    for (int i = 0; i < n; i++) {
        totalWaitingTime += waitingTimes[i];
        totalTurnaroundTime += turnaroundTimes[i];
    }

    float averageWaitingTime = static_cast<float>(totalWaitingTime) / n;
    float averageTurnaroundTime = static_cast<float>(totalTurnaroundTime) / n;

    std::cout << "Average Waiting Time: " << averageWaitingTime << std::endl;
    std::cout << "Average Turnaround Time: " << averageTurnaroundTime << std::endl;
}

int main() {
    std::vector<Process> processes = { {0, 10}, {6, 20}, {60, 5}, {110, 8} };

    calculateAverageTime(processes);

    return 0;
}

在上述示例中,定义了一个Process结构体来表示进程,包含到达时间和运行时间。calculateWaitingTime函数用于计算每个进程的等待时间,calculateTurnaroundTime函数用于计算每个进程的周转时间。calculateAverageTime函数调用上述两个函数并计算平均等待时间和平均周转时间。在main函数中,定义了一个进程数组,并传递给calculateAverageTime函数进行计算。

以上是一个基本的FCFS算法的实现,可以根据实际需求进行调整和扩展。

0
看了该问题的人还看了