设计一个按先来先服务,算法时间片轮转法,优先数调度算法实现处理器调度的程序。
时间: 2023-12-16 08:03:34 浏览: 82
设计一个按优先数调度算法实现处理器调度的程序。
以下是三个算法的处理器调度程序实现:
1. 先来先服务(FCFS):
```python
def fcfs(processes):
# 按照到达时间排序
processes.sort(key=lambda x: x[0])
# 初始化等待时间和周转时间
wait_time = 0
turnaround_time = 0
# 计算等待时间和周转时间
for i in range(len(processes)):
if i == 0:
wait_time = processes[i][0]
else:
wait_time += processes[i][0] - processes[i-1][1]
turnaround_time += processes[i][1] - processes[i][0]
# 计算平均等待时间和平均周转时间
avg_wait_time = wait_time / len(processes)
avg_turnaround_time = turnaround_time / len(processes)
# 打印结果
print(f"FCFS调度结果:")
print(f"平均等待时间:{avg_wait_time:.2f}")
print(f"平均周转时间:{avg_turnaround_time:.2f}")
```
2. 时间片轮转(Round Robin):
```python
def round_robin(processes, time_slice):
# 初始化等待时间和周转时间
wait_time = [0] * len(processes)
turnaround_time = [0] * len(processes)
# 初始化剩余时间
remaining_time = [process[1] for process in processes]
# 初始化当前时间和当前进程
current_time = 0
current_process = 0
# 开始轮转
while True:
# 如果所有进程都执行完毕,则退出循环
if all(x <= 0 for x in remaining_time):
break
# 如果当前进程的剩余时间为0,则寻找下一个进程
if remaining_time[current_process] == 0:
current_process = (current_process + 1) % len(processes)
continue
# 执行当前进程,更新剩余时间
if remaining_time[current_process] > time_slice:
current_time += time_slice
remaining_time[current_process] -= time_slice
else:
current_time += remaining_time[current_process]
remaining_time[current_process] = 0
# 计算等待时间和周转时间
wait_time[current_process] = current_time - processes[current_process][1]
turnaround_time[current_process] = current_time - processes[current_process][0]
# 寻找下一个进程
current_process = (current_process + 1) % len(processes)
# 计算平均等待时间和平均周转时间
avg_wait_time = sum(wait_time) / len(processes)
avg_turnaround_time = sum(turnaround_time) / len(processes)
# 打印结果
print(f"时间片轮转调度结果:")
print(f"平均等待时间:{avg_wait_time:.2f}")
print(f"平均周转时间:{avg_turnaround_time:.2f}")
```
3. 优先数调度(Priority Scheduling):
```python
def priority_scheduling(processes):
# 按照优先级排序
processes.sort(key=lambda x: x[2])
# 初始化等待时间和周转时间
wait_time = [0] * len(processes)
turnaround_time = [0] * len(processes)
# 执行进程
for i in range(len(processes)):
if i == 0:
current_time = processes[i][0]
else:
current_time = max(current_time, processes[i][0])
current_time += processes[i][1]
# 计算等待时间和周转时间
wait_time[i] = current_time - processes[i][1] - processes[i][0]
turnaround_time[i] = current_time - processes[i][0]
# 计算平均等待时间和平均周转时间
avg_wait_time = sum(wait_time) / len(processes)
avg_turnaround_time = sum(turnaround_time) / len(processes)
# 打印结果
print(f"优先数调度结果:")
print(f"平均等待时间:{avg_wait_time:.2f}")
print(f"平均周转时间:{avg_turnaround_time:.2f}")
```
以上程序均采用 Python 语言实现,其中 `processes` 是一个二维列表,每个元素代表一个进程,包含三个属性:到达时间、执行时间和优先级。
阅读全文