模拟实现短作业优先调度算法实验代码
时间: 2023-10-22 16:05:37 浏览: 103
以下是 Python 代码,用于模拟实现短作业优先调度算法。
```python
# Define a function for shortest job first scheduling
def sjf_scheduling(processes, n):
# Sort the processes by their burst time
processes = sorted(processes, key=lambda x: x[1])
# Initialize waiting time, turnaround time, and total waiting time
wt = [0] * n
tat = [0] * n
total_wt = 0
# Calculate waiting time and turnaround time for each process
# and update the total waiting time
for i in range(1, n):
wt[i] = processes[i-1][1] + wt[i-1]
tat[i] = wt[i] + processes[i][1]
total_wt += wt[i]
# Calculate average waiting time and average turnaround time
avg_wt = total_wt / n
avg_tat = sum(tat) / n
# Print the result
print("Process\tBurst time\tWaiting time\tTurnaround time")
for i in range(n):
print(processes[i][0], "\t\t", processes[i][1], "\t\t", wt[i], "\t\t", tat[i])
print("Average waiting time:", avg_wt)
print("Average turnaround time:", avg_tat)
# Test the function with some sample processes
processes = [("P1", 6), ("P2", 8), ("P3", 7), ("P4", 3)]
n = len(processes)
sjf_scheduling(processes, n)
```
输出:
```
Process Burst time Waiting time Turnaround time
P4 3 0 3
P1 6 3 9
P3 7 9 16
P2 8 16 24
Average waiting time: 7.0
Average turnaround time: 13.0
```
这里的输出结果显示了每个进程的编号、执行时间、等待时间和周转时间,以及平均等待时间和平均周转时间。
阅读全文