fcfs调度算法python实现
时间: 2023-09-03 21:06:00 浏览: 258
下面是一个使用 Python 实现 FCFS 调度算法的示例代码:
```python
class Process:
def __init__(self, pid, arrival_time, burst_time):
self.pid = pid
self.arrival_time = arrival_time
self.burst_time = burst_time
def fcfs(processes):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
# 计算第一个进程的等待时间
waiting_time[0] = 0
# 计算每个进程的等待时间和周转时间
for i in range(1, n):
waiting_time[i] = processes[i-1].burst_time + waiting_time[i-1]
turnaround_time[i-1] = waiting_time[i-1] + processes[i-1].burst_time
# 计算最后一个进程的周转时间
turnaround_time[n-1] = waiting_time[n-1] + processes[n-1].burst_time
# 计算平均等待时间和平均周转时间
avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n
# 打印每个进程的信息
print("Process\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
print(f"{processes[i].pid}\t\t{processes[i].arrival_time}\t\t{processes[i].burst_time}\t\t{waiting_time[i]}\t\t{turnaround_time[i]}")
# 打印平均等待时间和平均周转时间
print(f"\nAverage waiting time: {avg_waiting_time:.2f}")
print(f"Average turnaround time: {avg_turnaround_time:.2f}")
# 示例用法
if __name__ == "__main__":
processes = [
Process("P1", 0, 5),
Process("P2", 1, 3),
Process("P3", 2, 8),
Process("P4", 3, 6)
]
fcfs(processes)
```
输出结果如下:
```
Process Arrival Time Burst Time Waiting Time Turnaround Time
P1 0 5 0 5
P2 1 3 5 8
P3 2 8 8 16
P4 3 6 16 22
Average waiting time: 7.25
Average turnaround time: 12.75
```
其中,`Process` 类表示进程,包含进程 ID、到达时间和执行时间。`fcfs` 函数接受一个进程列表作为参数,计算每个进程的等待时间和周转时间,并输出结果。在示例中,我们创建了一个包含 4 个进程的列表,并将其作为参数传递给 `fcfs` 函数。
阅读全文