编程模拟实现进程调度算法(RR时间片轮转与HPF优先级调度算法
时间: 2023-12-03 15:44:20 浏览: 129
好的,下面是我实现的两种算法的代码:
## RR算法
```python
class Process:
def __init__(self, pid, arrival_time, burst_time):
self.pid = pid
self.arrival_time = arrival_time
self.burst_time = burst_time
self.remaining_time = burst_time
def RR(processes, quantum):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
time = 0
queue = []
i = 0
while True:
while i < n and processes[i].arrival_time <= time:
queue.append(processes[i])
i += 1
if not queue:
if i == n:
break
else:
time += 1
continue
process = queue.pop(0)
if process.remaining_time <= quantum:
for j in range(i, n):
if processes[j].arrival_time <= time:
waiting_time[j] += quantum if process == processes[j] else 0
time += process.remaining_time
turnaround_time[process.pid] = time - process.arrival_time
process.remaining_time = 0
else:
process.remaining_time -= quantum
for j in range(i, n):
if processes[j].arrival_time <= time:
waiting_time[j] += quantum if process == processes[j] else 0
queue.append(process)
time += quantum
if i == n and not queue:
break
avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n
return avg_waiting_time, avg_turnaround_time
```
## HPF算法
```python
class Process:
def __init__(self, pid, arrival_time, burst_time, priority):
self.pid = pid
self.arrival_time = arrival_time
self.burst_time = burst_time
self.remaining_time = burst_time
self.priority = priority
def HPF(processes):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
time = 0
queue = []
i = 0
while True:
while i < n and processes[i].arrival_time <= time:
queue.append(processes[i])
i += 1
if not queue:
if i == n:
break
else:
time += 1
continue
queue.sort(key=lambda x: (-x.priority, x.arrival_time))
process = queue.pop(0)
for j in range(i, n):
if processes[j].arrival_time <= time and process != processes[j]:
waiting_time[j] += process.burst_time
time += process.burst_time
turnaround_time[process.pid] = time - process.arrival_time
process.remaining_time = 0
if i == n and not queue:
break
avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n
return avg_waiting_time, avg_turnaround_time
```
以上是我实现的两种算法的代码,供你参考。
阅读全文