先来先服务和短作业优先调度算法代码
时间: 2023-10-22 21:14:21 浏览: 103
以下是先来先服务(FCFS)和短作业优先(SJF)调度算法的代码示例:
先来先服务(FCFS)调度算法:
```python
# FCFS调度算法
def fcfs(processes):
n = len(processes)
# 按照到达时间进行升序排序
processes = sorted(processes, key=lambda x: x[0])
# 计算等待时间和周转时间
waiting_time, turnaround_time = [0] * n, [0] * n
for i in range(1, n):
waiting_time[i] = waiting_time[i - 1] + processes[i - 1][1]
for i in range(n):
turnaround_time[i] = waiting_time[i] + processes[i][1]
# 计算平均等待时间和平均周转时间
avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n
# 返回结果
return avg_waiting_time, avg_turnaround_time
```
短作业优先(SJF)调度算法:
```python
# SJF调度算法
def sjf(processes):
n = len(processes)
# 按照到达时间进行升序排序
processes = sorted(processes, key=lambda x: x[0])
# 初始化等待时间和周转时间
waiting_time, turnaround_time = [0] * n, [0] * n
# 记录已经运行的时间
run_time = 0
# 记录已经完成的进程数
completed = 0
# 循环运行进程
while completed < n:
# 找到所有已经到达的进程
arrived_processes = [process for process in processes if process[0] <= run_time and process[3] == 0]
if not arrived_processes:
# 如果当前没有进程到达,则时间加1
run_time += 1
continue
# 找到运行时间最短的进程
shortest_process = min(arrived_processes, key=lambda x: x[1])
# 更新等待时间和周转时间
index = processes.index(shortest_process)
waiting_time[index] = run_time - shortest_process[0]
turnaround_time[index] = waiting_time[index] + shortest_process[1]
# 更新已经运行的时间和完成的进程数
run_time += shortest_process[1]
completed += 1
# 标记已经完成的进程
processes[index][3] = 1
# 计算平均等待时间和平均周转时间
avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n
# 返回结果
return avg_waiting_time, avg_turnaround_time
```
以上两个算法都是使用Python语言编写的。其中,`processes`是一个列表,表示进程的信息。每个进程由四个元素组成,依次为到达时间、运行时间、优先级(如果是SJF算法,优先级为运行时间)和完成标志(0表示未完成,1表示已完成)。这两个算法的返回值都是平均等待时间和平均周转时间。
阅读全文