使用C语言编写短作业优先调度算法,要求键盘输入作业请求,其中作业开始时间使用时钟法表示,并在最后输出平均周转时间和带权平均周转时间
时间: 2024-03-25 11:38:46 浏览: 18
下面是一个使用C语言编写短作业优先调度算法的示例。该算法要求从键盘输入作业请求,其中作业开始时间使用时钟法表示,并在最后输出平均周转时间和带权平均周转时间。
```c
#include <stdio.h>
#include <stdlib.h>
struct Job {
int id; // 作业ID
int arrival_time; // 到达时间
int execution_time; // 执行时间
int finish_time; // 完成时间
int turnaround_time; // 周转时间
float weighted_turnaround_time; // 带权周转时间
};
void swap(struct Job *a, struct Job *b) {
struct Job temp = *a;
*a = *b;
*b = temp;
}
void sort_jobs(struct Job *jobs, int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (jobs[j].execution_time > jobs[j+1].execution_time) {
swap(&jobs[j], &jobs[j+1]);
}
}
}
}
void schedule_jobs(struct Job *jobs, int n) {
sort_jobs(jobs, n);
int current_time = 0;
for (int i = 0; i < n; i++) {
jobs[i].arrival_time = current_time;
jobs[i].finish_time = current_time + jobs[i].execution_time;
jobs[i].turnaround_time = jobs[i].finish_time - jobs[i].arrival_time;
jobs[i].weighted_turnaround_time = (float) jobs[i].turnaround_time / jobs[i].execution_time;
current_time = jobs[i].finish_time;
}
float total_turnaround_time = 0;
float total_weighted_turnaround_time = 0;
for (int i = 0; i < n; i++) {
total_turnaround_time += jobs[i].turnaround_time;
total_weighted_turnaround_time += jobs[i].weighted_turnaround_time;
printf("Job %d: arrival time=%d, execution time=%d, finish time=%d, turnaround time=%d, weighted turnaround time=%.2f\n",
jobs[i].id, jobs[i].arrival_time, jobs[i].execution_time, jobs[i].finish_time, jobs[i].turnaround_time, jobs[i].weighted_turnaround_time);
}
printf("Average turnaround time: %.2f\n", total_turnaround_time / n);
printf("Average weighted turnaround time: %.2f\n", total_weighted_turnaround_time / n);
}
int main() {
int n;
printf("Enter the number of jobs: ");
scanf("%d", &n);
struct Job *jobs = (struct Job *) malloc(n * sizeof(struct Job));
for (int i = 0; i < n; i++) {
printf("Enter the execution time of job %d: ", i+1);
scanf("%d", &jobs[i].execution_time);
jobs[i].id = i+1;
}
schedule_jobs(jobs, n);
free(jobs);
return 0;
}
```
在该示例中,我们定义了一个作业结构体,包含作业ID、到达时间、执行时间、完成时间、周转时间和带权周转时间等字段。在sort_jobs函数中,我们使用冒泡排序算法将作业按照执行时间从小到大排序。在schedule_jobs函数中,我们先调用sort_jobs函数将作业排序,然后依次执行作业,计算各个字段的值。最后输出每个作业的详细信息以及平均周转时间和带权平均周转时间。在main函数中,我们先从键盘读入作业数量,然后依次读入每个作业的执行时间,构建作业数组,最后调用schedule_jobs函数进行作业调度。
注意:这个示例中实现的短作业优先调度算法是非抢占式的,即一旦一个作业开始执行,就不会被打断。如果需要实现抢占式的短作业优先调度算法,需要在调度过程中动态地修改队列中作业的执行顺序。