先来先服务算法 python实现
时间: 2023-11-02 18:06:05 浏览: 97
排序算法的python实现
先来先服务(First-Come, First-Served,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
total_waiting_time = 0
total_turnaround_time = 0
current_time = 0
for i in range(n):
if current_time < processes[i].arrival_time:
current_time = processes[i].arrival_time
waiting_time[i] = current_time - processes[i].arrival_time
turnaround_time[i] = waiting_time[i] + processes[i].burst_time
current_time += processes[i].burst_time
total_waiting_time += waiting_time[i]
total_turnaround_time += turnaround_time[i]
avg_waiting_time = total_waiting_time / n
avg_turnaround_time = total_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"Average waiting time: {avg_waiting_time:.2f}")
print(f"Average turnaround time: {avg_turnaround_time:.2f}")
# 示例用法
processes = [Process(1, 0, 5), Process(2, 1, 3), Process(3, 2, 8)]
fcfs(processes)
```
阅读全文