0% found this document useful (0 votes)
10 views4 pages

FCFS and SJF CPU Scheduling Algorithms

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

FCFS and SJF CPU Scheduling Algorithms

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program 3

AIM: Implementation of FCFS and SJF cpu scheduling algorithms


CODE:
class Process:
def __init__(self, pid, arrival_time, burst_time):

[Link] = pid

self.arrival_time = arrival_time

self.burst_time = burst_time

self.waiting_time = 0

def fcfs_scheduler(processes):

[Link](key=lambda x: x.arrival_time)

current_time = 0

total_waiting_time = 0

print("\n\nFCFS Scheduling:")

print("PID\tA.T.\tB.T.\tW.T.")

for process in processes:

if process.arrival_time > current_time:

current_time = process.arrival_time

process.waiting_time = current_time - process.arrival_time

total_waiting_time += process.waiting_time
print(f"{[Link]}\t\t{process.arrival_time}\t\t{process.burst_time}\t\t{process.
waiting_time}")

current_time += process.burst_time

average_waiting_time = total_waiting_time / len(processes)

print(f"Average Waiting Time: {average_waiting_time:.2f}")

def sjf_scheduler(processes):

[Link](key=lambda x: x.arrival_time)

n = len(processes)

current_time = 0

total_waiting_time = 0

completed = 0

waiting_queue = []

print("\n\nSJF Scheduling:")

print("PID\tA.T.\tB.T.\tW.T.")

while completed < n:

# Add processes that have arrived by current_time to the waiting_queue

for process in processes:

if process.arrival_time <= current_time and process not in waiting_queue:


waiting_queue.append(process)

if not waiting_queue:

current_time = min(processes, key=lambda p: p.arrival_time).arrival_time

continue

# Select process with the shortest burst time from the queue

waiting_queue.sort(key=lambda x: x.burst_time)

current_process = waiting_queue.pop(0)

current_process.waiting_time = current_time - current_process.arrival_time

total_waiting_time += current_process.waiting_time

print(f"{current_process.pid}\t\t{current_process.arrival_time}\t\t{current_process
.burst_time}\t\t{current_process.waiting_time}")

current_time += current_process.burst_time

completed += 1

average_waiting_time = total_waiting_time / n

print(f"Average Waiting Time: {average_waiting_time:.2f}")

if __name__ == "__main__":

n = int(input("Enter the number of processes: "))

processes = []

for i in range(n):
pid = i + 1

arrival_time = int(input(f"Enter arrival time for Process {pid}: "))

burst_time = int(input(f"Enter burst time for Process {pid}: "))

[Link](Process(pid, arrival_time, burst_time))

fcfs_scheduler([Link]())

sjf_scheduler([Link]())

CODE OUTPUT:

You might also like