首先,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算法的實現,可以根據實際需求進行調整和擴展。