用c++语言设计先来先服务调度(FCFS)和按短作业优先调度算法(SJF),输入作业数目,到达时间,服务时间,输出完成时间,周转时间,带权周转时间,这一组作业完成后计算并输出这组作业的平均周转时间、平均带权周转时间
时间: 2024-11-17 08:30:54 浏览: 18
在C++中,我们可以设计两个简单的调度算法,即先来先服务(FCFS)和短作业优先(SJF)。这里我们仅提供算法的基本框架,实际完整实现需要包含数据结构(如队列)、函数以及主程序。
首先,假设有一个Job类,存储作业的相关信息:
```cpp
class Job {
public:
int arrival_time;
int service_time;
bool is_completed = false;
// 构造函数
Job(int arr, int serv) : arrival_time(arr), service_time(serv) {}
};
```
1. 先来先服务 (FCFS) 算法:
```cpp
struct FCFS_Scheduler {
std::queue<Job> jobs;
void enqueue(Job job) {
jobs.push(job);
}
void schedule() {
while (!jobs.empty()) {
Job current = jobs.front();
if (current.arrival_time == 0) {
process(current);
jobs.pop();
} else {
break;
}
}
}
private:
void process(Job& job) {
for (int i = 0; i < job.service_time; ++i) {
if (job.is_completed) {
break;
}
}
job.is_completed = true;
}
};
```
2. 短作业优先 (SJF) 算法:
```cpp
struct SJF_Scheduler {
std::priority_queue<Job, std::vector<Job>, std::greater<Job>> priority_queue;
void enqueue(Job job) {
priority_queue.push(job);
}
void schedule() {
while (!priority_queue.empty()) {
Job current = priority_queue.top();
priority_queue.pop();
process(current);
}
}
private:
// ... (process function类似FCFS)
};
```
当所有作业完成后,可以计算周转时间和带权周转时间:
```cpp
void calculateTurnaroundTimes(const std::vector<Job>& jobs) {
double total_turnaround = 0;
double weighted_turnaround = 0;
for (const auto& job : jobs) {
total_turnaround += job.arrival_time + job.service_time - job.completion_time;
weighted_turnaround += job.service_time * (job.arrival_time + job.service_time - job.completion_time);
}
double average_turnaround = total_turnaround / jobs.size();
double average_weighted_turnaround = weighted_turnaround / jobs.size();
// 输出结果
std::cout << "Average Turnaround Time: " << average_turnaround << std::endl;
std::cout << "Average Weighted Turnaround Time: " << average_weighted_turnaround << std::endl;
}
```
阅读全文