编制时间片轮转调度算法和静态优先级调度算法代码
时间: 2024-03-09 21:44:25 浏览: 74
时间片轮转调度算法的代码如下:
```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 execute(self, time_slice):
if self.remaining_time > time_slice:
self.remaining_time -= time_slice
return time_slice
else:
time_executed = self.remaining_time
self.remaining_time = 0
return time_executed
def round_robin_scheduling(processes, time_slice):
n = len(processes)
remaining_processes = processes.copy()
current_time = 0
waiting_time = 0
turnaround_time = 0
while remaining_processes:
current_process = remaining_processes.pop(0)
if current_process.arrival_time > current_time:
current_time = current_process.arrival_time
time_executed = current_process.execute(time_slice)
current_time += time_executed
if current_process.remaining_time == 0:
waiting_time += current_time - current_process.arrival_time - current_process.burst_time
turnaround_time += current_time - current_process.arrival_time
else:
remaining_processes.append(current_process)
avg_waiting_time = waiting_time / n
avg_turnaround_time = turnaround_time / n
return avg_waiting_time, avg_turnaround_time
```
静态优先级调度算法的代码如下:
```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.priority = priority
def execute(self):
self.burst_time -= 1
def static_priority_scheduling(processes):
n = len(processes)
remaining_processes = processes.copy()
current_time = 0
waiting_time = 0
turnaround_time = 0
while remaining_processes:
remaining_processes.sort(key=lambda x: (x.priority, x.arrival_time))
current_process = remaining_processes.pop(0)
if current_process.arrival_time > current_time:
current_time = current_process.arrival_time
current_process.execute()
current_time += 1
if current_process.burst_time == 0:
waiting_time += current_time - current_process.arrival_time - current_process.priority
turnaround_time += current_time - current_process.arrival_time
else:
remaining_processes.append(current_process)
avg_waiting_time = waiting_time / n
avg_turnaround_time = turnaround_time / n
return avg_waiting_time, avg_turnaround_time
```
阅读全文