用c语言写一个时间片轮转调度模拟算法并给出代码
时间: 2024-01-28 14:05:28 浏览: 77
时间片轮转算法的是想用C语言
5星 · 资源好评率100%
很高兴为您服务!以下是时间片轮转调度模拟算法的 C 语言代码实现:
```c
#include<stdio.h>
struct Process
{
int pid; // 进程号
int arrival_time; // 到达时间
int burst_time; // 执行时间
int remaining_time; // 剩余执行时间
int waiting_time; // 等待时间
int turnaround_time; // 周转时间
};
int main()
{
int n, i, j, tq, time = 0, flag = 0, total_waiting_time = 0, total_turnaround_time = 0;
struct Process p[10], temp;
float avg_waiting_time, avg_turnaround_time;
printf("Enter the number of processes: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter details of process %d:\n", i + 1);
p[i].pid = i + 1;
printf("Arrival time: ");
scanf("%d", &p[i].arrival_time);
printf("Burst time: ");
scanf("%d", &p[i].burst_time);
p[i].remaining_time = p[i].burst_time;
printf("\n");
}
printf("Enter time quantum: ");
scanf("%d", &tq);
// Sorting the processes based on arrival time
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - i - 1; j++)
{
if(p[j].arrival_time > p[j + 1].arrival_time)
{
temp = p[j];
p[j] = p[j + 1];
p[j + 1] = temp;
}
}
}
// Time slice algorithm
printf("\nGantt chart:\n");
printf("%d ", time);
do
{
flag = 0;
for(i = 0; i < n; i++)
{
if(p[i].remaining_time > 0)
{
flag = 1;
if(p[i].remaining_time > tq)
{
time += tq;
p[i].remaining_time -= tq;
printf("-- %d P%d -- ", time, p[i].pid);
}
else
{
time += p[i].remaining_time;
p[i].waiting_time = time - p[i].arrival_time - p[i].burst_time;
p[i].turnaround_time = time - p[i].arrival_time;
total_waiting_time += p[i].waiting_time;
total_turnaround_time += p[i].turnaround_time;
p[i].remaining_time = 0;
printf("-- %d P%d -- ", time, p[i].pid);
}
}
}
} while(flag);
// Printing the waiting time and turnaround time for each process
printf("\n\nProcess details:\n\n");
printf("PID Arrival Time Burst Time Waiting Time Turnaround Time\n");
for(i = 0; i < n; i++)
{
printf("%2d\t%11d\t%10d\t%12d\t%15d\n", p[i].pid, p[i].arrival_time, p[i].burst_time, p[i].waiting_time, p[i].turnaround_time);
}
// Calculating the average waiting time and turnaround time
avg_waiting_time = (float) total_waiting_time / n;
avg_turnaround_time = (float) total_turnaround_time / n;
printf("\nAverage waiting time: %0.2f", avg_waiting_time);
printf("\nAverage turnaround time: %0.2f", avg_turnaround_time);
return 0;
}
```
希望对您有帮助!如果您有任何其他问题,都可以问我哦~
阅读全文