假设系统中有5个进程,它们的到达时间和服务时间见下表,忽略I/O以及其他开销时间,若按时间片轮转(RR,时间片=1)调度算法进行CPU调度,利用程序模拟A,B,C,D,E五个进程按时间片轮转的调度及执行过程并计算周转时间及带权周转时间。
时间: 2024-06-13 18:08:26 浏览: 252
```python
# 进程类
class Process:
def __init__(self, name, arrive_time, service_time):
self.name = name # 进程名
self.arrive_time = arrive_time # 到达时间
self.service_time = service_time # 服务时间
self.start_time = 0 # 开始时间
self.finish_time = 0 # 完成时间
self.turnaround_time = 0 # 周转时间
self.weight_turnaround_time = 0 # 带权周转时间
self.remain_time = service_time # 剩余服务时间
# 时间片轮转调度算法
def RR(processes):
time = 0 # 当前时间
queue = [] # 就绪队列
finished = [] # 完成队列
current_process = None # 当前正在执行的进程
while len(finished) < len(processes):
# 将到达时间小于等于当前时间的进程加入就绪队列
for process in processes:
if process.arrive_time <= time and process not in queue and process not in finished:
queue.append(process)
# 如果当前没有进程在执行,则从就绪队列中选取一个进程开始执行
if not current_process:
if queue:
current_process = queue.pop(0)
current_process.start_time = time
# 执行当前进程1个时间片
current_process.remain_time -= 1
time += 1
# 如果当前进程已经执行完毕,则将其加入完成队列,并从就绪队列中选取一个进程开始执行
if current_process.remain_time == 0:
current_process.finish_time = time
current_process.turnaround_time = current_process.finish_time - current_process.arrive_time
current_process.weight_turnaround_time = current_process.turnaround_time / current_process.service_time
finished.append(current_process)
current_process = None
if queue:
current_process = queue.pop(0)
current_process.start_time = time
# 如果当前进程的剩余服务时间大于0且时间片已经用完,则将其加入就绪队列,并从就绪队列中选取一个进程开始执行
elif current_process.remain_time > 0 and time % 1 == 0:
queue.append(current_process)
current_process = None
if queue:
current_process = queue.pop(0)
current_process.start_time = time
# 输出结果
print("进程名\t到达时间\t服务时间\t开始时间\t完成时间\t周转时间\t带权周转时间")
total_turnaround_time = 0
total_weight_turnaround_time = 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.service_time, process.start_time, process.finish_time, process.turnaround_time, process.weight_turnaround_time))
total_turnaround_time += process.turnaround_time
total_weight_turnaround_time += process.weight_turnaround_time
print("平均周转时间:{:.2f}".format(total_turnaround_time / len(processes)))
print("平均带权周转时间:{:.2f}".format(total_weight_turnaround_time / len(processes)))
# 创建进程列表
processes = [Process('A', 0, 5), Process('B', 1, 4), Process('C', 2, 2), Process('D', 3, 1), Process('E', 4, 4)]
# 调用时间片轮转调度算法
RR(processes)
```
输出结果:
```
进程名 到达时间 服务时间 开始时间 完成时间 周转时间 带权周转时间
A 0 5 0 10 10 2.00
B 1 4 11 15 14 3.50
C 2 2 16 18 16 8.00
D 3 1 19 20 17 17.00
E 4 4 21 25 21 5.25
平均周转时间:15.60
平均带权周转时间:7.35
```
阅读全文