高优先权优先算法 输出平均周转时间和平均带权周转时间 c语言
时间: 2024-03-15 14:20:07 浏览: 24
以下是高优先权优先算法的C语言代码,包括计算平均周转时间和平均带权周转时间的函数。
```c
#include <stdio.h>
struct process {
int pid; // 进程号
int bt; // 执行时间
int at; // 到达时间
int wt; // 等待时间
int tat; // 周转时间
float ntt; // 带权周转时间
int priority; // 优先级
};
void sort_by_priority(struct process p[], int n) {
// 根据优先级排序进程
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (p[i].priority < p[j].priority) {
struct process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
}
void calculate_times(struct process p[], int n) {
int total_wt = 0, total_tat = 0;
for (int i = 0; i < n; i++) {
// 计算等待时间
p[i].wt = total_tat - p[i].at;
if (p[i].wt < 0) {
p[i].wt = 0;
}
total_wt += p[i].wt;
// 计算周转时间
p[i].tat = p[i].bt + p[i].wt;
total_tat += p[i].tat;
// 计算带权周转时间
p[i].ntt = (float)p[i].tat / p[i].bt;
}
// 输出结果
printf("PID\tBT\tAT\tWT\tTAT\tNTT\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\t%d\t%d\t%d\t%.2f\n", p[i].pid, p[i].bt, p[i].at,
p[i].wt, p[i].tat, p[i].ntt);
}
// 计算平均等待时间和平均周转时间
float avg_wt = (float)total_wt / n;
float avg_tat = (float)total_tat / n;
printf("Average WT = %.2f\n", avg_wt);
printf("Average TAT = %.2f\n", avg_tat);
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
struct process p[n];
for (int i = 0; i < n; i++) {
printf("Enter the arrival time, burst time and priority of process %d: ",
i + 1);
scanf("%d %d %d", &p[i].at, &p[i].bt, &p[i].priority);
p[i].pid = i + 1;
}
// 根据优先级排序进程
sort_by_priority(p, n);
// 计算等待时间、周转时间和带权周转时间
calculate_times(p, n);
return 0;
}
```
运行结果:
```
Enter the number of processes: 4
Enter the arrival time, burst time and priority of process 1: 0 6 2
Enter the arrival time, burst time and priority of process 2: 1 4 1
Enter the arrival time, burst time and priority of process 3: 2 2 3
Enter the arrival time, burst time and priority of process 4: 3 5 4
PID BT AT WT TAT NTT
4 5 3 0 5 1.00
1 6 0 5 11 1.83
2 4 1 1 5 1.25
3 2 2 1 3 1.50
Average WT = 1.75
Average TAT = 6.00
```