假设系统中有5个进程,它们的到达时间和服务时间见下表,忽略I/O以及其他开销时间,若按时间片轮转(RR,时间片=1)调度算法进行CPU调度,利用程序模拟A,B,C,D,E五个进程按时间片轮转的调度及执
时间: 2024-06-13 16:08:45 浏览: 249
```python
# 进程类
class Process:
def __init__(self, name, arrive_time, serve_time):
self.name = name # 进程名
self.arrive_time = arrive_time # 到达时间
self.serve_time = serve_time # 服务时间
self.start_time = 0 # 开始时间
self.finish_time = 0 # 完成时间
self.turnover_time = 0 # 周转时间
self.wait_time = 0 # 等待时间
self.response_ratio = 0 # 响应比
self.remaining_time = serve_time # 剩余服务时间
# 时间片轮转算法
def RR(processes):
time_slice = 1 # 时间片大小
current_time = 0 # 当前时间
finished_processes = [] # 已完成的进程
ready_queue = [] # 就绪队列
while len(finished_processes) < len(processes):
# 将到达时间小于等于当前时间的进程加入就绪队列
for process in processes:
if process.arrive_time <= current_time and process not in finished_processes and process not in ready_queue:
ready_queue.append(process)
# 如果就绪队列为空,则时间跳转到下一个进程的到达时间
if len(ready_queue) == 0:
current_time = processes[0].arrive_time
continue
# 取出队首进程
current_process = ready_queue.pop(0)
# 如果剩余服务时间小于等于时间片大小,则直接执行完该进程
if current_process.remaining_time <= time_slice:
current_time += current_process.remaining_time
current_process.finish_time = current_time
current_process.turnover_time = current_process.finish_time - current_process.arrive_time
current_process.wait_time = current_process.turnover_time - current_process.serve_time
current_process.response_ratio = (current_process.turnover_time / current_process.serve_time)
finished_processes.append(current_process)
# 否则,执行一个时间片
else:
current_time += time_slice
current_process.remaining_time -= time_slice
# 将该进程加入就绪队列的末尾
ready_queue.append(current_process)
# 输出结果
print("进程名\t到达时间\t服务时间\t完成时间\t周转时间\t等待时间\t响应比")
total_turnover_time = 0
total_wait_time = 0
total_response_ratio = 0
for process in processes:
print("{}\t{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{:.2f}".format(process.name, process.arrive_time, process.serve_time, process.finish_time, process.turnover_time, process.wait_time, process.response_ratio))
total_turnover_time += process.turnover_time
total_wait_time += process.wait_time
total_response_ratio += process.response_ratio
avg_turnover_time = total_turnover_time / len(processes)
avg_wait_time = total_wait_time / len(processes)
avg_response_ratio = total_response_ratio / len(processes)
print("平均周转时间:{:.2f}".format(avg_turnover_time))
print("平均等待时间:{:.2f}".format(avg_wait_time))
print("平均带权周转时间:{:.2f}".format(avg_response_ratio))
# 创建进程列表
processes = []
processes.append(Process('A', 0, 5))
processes.append(Process('B', 1, 3))
processes.append(Process('C', 2, 1))
processes.append(Process('D', 3, 2))
processes.append(Process('E', 4, 4))
# 调用时间片轮转算法
RR(processes)
```
阅读全文