python实现RR算法
时间: 2024-12-26 10:17:18 浏览: 19
### Python 实现 RR 轮转调度算法
RR(Round Robin,时间片轮转)是一种常见的进程调度算法。在此算法下,每个进程被分配一个固定长度的时间片,称为量子时间。如果进程在时间片内未完成执行,则会被中断并将剩余部分重新加入到就绪队列末尾。
下面是一个简单的Python实现示例:
```python
class Process:
def __init__(self, pid, arrival_time, burst_time):
self.pid = pid # 进程ID
self.arrival_time = arrival_time # 到达时刻
self.burst_time = burst_time # 需要的服务时间
self.remaining_time = burst_time # 剩余服务时间
self.waiting_time = 0 # 等待时间
def round_robin(processes, time_quantum):
n = len(processes)
total_waiting_time = 0
completed_processes = []
current_time = 0
while processes or completed_processes:
if not processes and all(p['remaining_time'] == 0 for p in completed_processes): break
to_run = None
i = 0
while True:
if i >= len(processes):
break
process = processes[i]
if process.arrival_time <= current_time:
to_run = process
del processes[i]
break
i += 1
if to_run is None:
current_time += 1
continue
if to_run.remaining_time > time_quantum:
current_time += time_quantum
to_run.remaining_time -= time_quantum
processes.append(to_run) # 将未完成的任务放回队列末尾
else:
current_time += to_run.remaining_time
to_run.waiting_time = (current_time - to_run.arrival_time - to_run.burst_time)
total_waiting_time += to_run.waiting_time
completed_processes.append({
'pid': to_run.pid,
'arrival_time': to_run.arrival_time,
'burst_time': to_run.burst_time,
'waiting_time': to_run.waiting_time,
'turnaround_time': current_time - to_run.arrival_time,
'completion_time': current_time,
'remaining_time': 0
})
avg_waiting_time = total_waiting_time / n
print(f'Average Waiting Time: {avg_waiting_time:.2f}')
if __name__ == '__main__':
# 测试数据集
test_cases = [
{'processes': [(1, 0, 8), (2, 1, 4)], 'time_quantum': 2},
{'processes': [(1, 0, 7), (2, 2, 4), (3, 4, 1)], 'time_quantum': 3}
]
for case in test_cases:
processes = [Process(pid=p[0], arrival_time=p[1], burst_time=p[2]) for p in case['processes']]
print("\nTest Case:")
for proc in processes:
print(f"P{proc.pid}: Arrival={proc.arrival_time}, Burst={proc.burst_time}")
round_robin(processes=processes[:], time_quantum=case['time_quantum'])
```
此代码定义了一个`Process`类用于表示单个进程,并实现了基本的RR调度逻辑函数`round_robin()`。测试用例展示了不同场景下的输入参数以及预期输出结果[^3]。
阅读全文