📅  最后修改于: 2023-12-03 15:22:25.145000             🧑  作者: Mango
最短作业优先(SJF)是一个非抢占式算法,它按照作业的预计执行时间(或所需 CPU 周期数)来选择最短的作业运行。
这个算法可以通过一个使用段树实现的优先队列来实现。
class SegmentTree:
def __init__(self, n):
self.tree = [None] * 4 * n
self.lazy = [None] * 4 * n
def update_lazy(self, node, start, end):
if self.lazy[node]:
self.tree[node] += self.lazy[node]
if start != end:
self.lazy[node * 2] = self.lazy[node]
self.lazy[node * 2 + 1] = self.lazy[node]
self.lazy[node] = None
def update_range(self, node, start, end, left, right, value):
self.update_lazy(node, start, end)
if right < start or end < left:
return
if left <= start and end <= right:
self.tree[node] += value
if start != end:
self.lazy[node * 2] = value
self.lazy[node * 2 + 1] = value
return
mid = (start + end) // 2
self.update_range(node * 2, start, mid, left, right, value)
self.update_range(node * 2 + 1, mid + 1, end, left, right, value)
self.tree[node] = min(self.tree[node * 2], self.tree[node * 2 + 1])
def query(self, node, start, end, left, right):
self.update_lazy(node, start, end)
if right < start or end < left:
return float('inf')
if left <= start and end <= right:
return self.tree[node]
mid = (start + end) // 2
return min(self.query(node * 2, start, mid, left, right),
self.query(node * 2 + 1, mid + 1, end, left, right))
class Process:
def __init__(self, pid, burst):
self.pid = pid
self.burst = burst
class SJF:
def __init__(self, processes):
self.processes = [Process(i, b) for i, b in enumerate(processes)]
self.processes.sort(key=lambda p: p.burst)
self.segment_tree = SegmentTree(len(self.processes))
def run(self):
print('SJF (Non-preemptive) Scheduling:')
print(f"|{'Process':^10}|{'Burst Time':^12}|{'Waiting Time':^14}|{'Turnaround Time':^19}|")
print('-' * 59)
time = 0
wait_times = [0] * len(self.processes)
for i, p in enumerate(self.processes):
wait_times[p.pid] = time
self.segment_tree.update_range(1, 0, len(self.processes) - 1, p.pid, p.pid, p.burst)
time += p.burst
print(f"|{p.pid:^10}|{p.burst:^12}|{wait_times[p.pid]:^14}|{(time - wait_times[p.pid]):^19}|")
avg_wait_time = sum(wait_times) / len(self.processes)
avg_turnaround_time = sum([p.burst for p in self.processes]) / len(self.processes)
print(f"\nAverage Waiting Time: {avg_wait_time:.4f}")
print(f"Average Turnaround Time: {avg_turnaround_time:.4f}")
使用段树的最短作业优先(SJF)算法是一种非常高效、简单且易于实现的 CPU 调度算法,它可以大大降低 CPU 的等待时间,提高系统的响应速度。通过使用 Python 语言的代码示例,读者可以深入了解如何使用 Python 实现这个算法,并对算法的时间复杂度进行分析。