3
1
SystemsProgrammingAndOperat.../Codes/Python version/Assignment-A5 (CPU Scheduling)/SJF.py

49 lines
1.4 KiB
Python

import sys
def sjf_preemptive(processes, n):
remaining_time = [bt for _, _, bt in processes]
complete = 0
t = 0
minm = sys.maxsize
shortest = 0
finish_time = 0
check = False
waiting_time = [0] * n
turnaround_time = [0] * n
while complete != n:
for j in range(n):
if processes[j][1] <= t and remaining_time[j] < minm and remaining_time[j] > 0:
minm = remaining_time[j]
shortest = j
check = True
if not check:
t += 1
continue
remaining_time[shortest] -= 1
minm = remaining_time[shortest] if remaining_time[shortest] > 0 else sys.maxsize
if remaining_time[shortest] == 0:
complete += 1
check = False
finish_time = t + 1
waiting_time[shortest] = finish_time - processes[shortest][2] - processes[shortest][1]
if waiting_time[shortest] < 0:
waiting_time[shortest] = 0
t += 1
for i in range(n):
turnaround_time[i] = processes[i][2] + waiting_time[i]
print("\nSJF (Preemptive) Scheduling:")
for i, process in enumerate(processes):
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
# Input: Process ID, Arrival Time, Burst Time
processes = [[1, 0, 8], [2, 1, 4], [3, 2, 9], [4, 3, 5]]
sjf_preemptive(processes, len(processes))