0% found this document useful (0 votes)
23 views

Os Code

Uploaded by

gamebymrinmoy
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)
23 views

Os Code

Uploaded by

gamebymrinmoy
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
You are on page 1/ 10

Assignment 4

FCFS
SOURCE CODE:
import matplotlib.pyplot as plt
print("FIRST COME FIRST SERVE SCHEDULING")
def calculate_metrics(processes, n, bt):
wt = [0] * n
tat = [0] * n
rt = [0] * n # Add a list for response time
ct = [0] * n
ct[0] = bt[0]
for i in range(1, n):
ct[i] = ct[i - 1] + bt[i]
for i in range(n):
tat[i] = ct[i] - processes[i][1]
wt[i] = tat[i] - processes[i][2]
rt[i] = ct[i] # Response time is the same as waiting time for
FCFS
avg_tat = sum(tat) / n
avg_wt = sum(wt) / n
avg_rt = sum(rt) / n # Calculate average response time
return ct, tat, wt, rt, avg_tat, avg_wt, avg_rt
def main():
n = int(input("Enter the number of processes: "))
processes = []
for i in range(n):
arrival_time = int(input(f"Enter arrival time for process {i + 1}:
"))
burst_time = int(input(f"Enter burst time for process {i + 1}: "))
processes.append((i + 1, arrival_time, burst_time))
processes.sort(key=lambda x: x[1])
burst_time_list = [process[2] for process in processes]
completion_time, turnaround_time, waiting_time, response_time,
avg_turnaround_time, avg_waiting_time, avg_response_time =
calculate_metrics(processes, n, burst_time_list)
print("\nProcess\tArrival Time\tBurst Time\tCompletion
Time\tTurnaround Time\tWaiting Time\tResponse Time")
for i in range(n):
print(f"P{i +
1}\t{processes[i][1]}\t\t{processes[i][2]}\t\t{completion_time[i]}\t\t{tur
naround_time[i]}\t\t{waiting_time[i]}\t\t{response_time[i]}")
print(f"\nAverage Turnaround Time: {avg_turnaround_time}")
print(f"Average Waiting Time: {avg_waiting_time}")
print(f"Average Response Time: {avg_response_time}")

# Create a Gantt chart


'''plt.figure(figsize=(10, 4))
for i in range(n):
plt.barh(f'P{processes[i][0]}', completion_time[i] -
processes[i][1], left=processes[i][1], color='tab:blue')
plt.xlabel('Time')
plt.ylabel('Processes')
plt.title('Gantt Chart (FCFS)')
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()'''
plt.figure(figsize=(10, 4))
plt.title("Gantt Chart - FCFS Scheduling")
for i in range(n):
plt.barh(y=0, width=burst_time_list[i], left=completion_time[i] -
burst_time_list[i], height=0.5)
plt.yticks([])
plt.xlabel("Time")
plt.show()
main()

OUTPUT:
FIRST COME FIRST SERVE SCHEDULING
Enter the number of processes: 3
Enter arrival time for process 1: 0
Enter burst time for process 1: 10
Enter arrival time for process 2: 1
Enter burst time for process 2: 5
Enter arrival time for process 3: 3
Enter burst time for process 3: 2
Process Arrival Time Burst Time Completion Time Turnaround Time Waiting Time Response Time
P1 0 10 10 10 0 10
P2 1 5 15 14 9 15
P3 3 2 17 14 12 17

Average Turnaround Time: 12.666666666666666


Average Waiting Time: 7.0
Average Response Time: 14.0
SJF NON PRE-EMPTIVE:
SOURCE CODE:
def calculate_metrics(processes):
n = len(processes)
wt, tat, ct, rt = [0] * n, [0] * n, [0] * n, [0] * n
completed = [False] * n
time = 0
for i in range(n):
min_bt = float('inf')
shortest = None
for j in range(n):
if not completed[j] and processes[j][1] <= time:
if processes[j][2] < min_bt:
min_bt = processes[j][2]
shortest = j
if shortest is None:
for j in range(n):
if not completed[j]:
time = processes[j][1]
break
completed[shortest] = True
# Calculate response time
rt[shortest] = time - processes[shortest][1]
time += processes[shortest][2]
ct[shortest] = time
tat[shortest] = ct[shortest] - processes[shortest][1]
wt[shortest] = tat[shortest] - processes[shortest][2]
avg_tat = sum(tat) / n
avg_wt = sum(wt) / n
avg_rt = sum(rt) / n
return ct, tat, wt, rt, avg_tat, avg_wt, avg_rt
def plot_gantt_chart(processes, ct):
fig, ax = plt.subplots(figsize=(10, 4))
sorted_processes = sorted(processes, key=lambda x: x[2]) # Sort
processes by burst time (SJF)
for i, (pid, at, bt) in enumerate(sorted_processes):
start_time = max(at, ct[i - 1] if i > 0 else 0)
ax.barh(f'P{pid}', left=start_time, width=bt, label=f'P{pid}')
ct[i] = start_time + bt # Update the completion time
ax.set_xlabel('Time')
ax.set_yticks([f'P{p[0]}' for p in sorted_processes])
ax.set_title('Gantt Chart')
plt.legend(loc='upper right')
plt.show()
def main():
n = int(input("Enter the number of processes: "))
processes = [(i + 1, int(input(f"Arrival time for P{i + 1}: ")),
int(input(f"Burst time for P{i + 1}: "))) for i in range(n)]
ct, tat, wt, rt, avg_tat, avg_wt, avg_rt =
calculate_metrics(processes)
print("\nProcess\tArrival Time\tBurst Time\tCompletion
Time\tTurnaround Time\tWaiting Time\tResponse Time")
for i in range(n):
pid, at, bt = processes[i]
print(f"P{pid}\t{at}\t\t{bt}\t\t{ct[i]}\t\t{tat[i]}\t\t{wt[i]}\t\t
{rt[i]}")
print(f"\nAverage Turnaround Time: {avg_tat}")
print(f"Average Waiting Time: {avg_wt}")
print(f"Average Response Time: {avg_rt}")
plot_gantt_chart(processes, ct)
main()

OUTPUT:
Enter the number of processes: 4
Arrival time for P1: 0
Burst time for P1: 6
Arrival time for P2: 0
Burst time for P2: 8
Arrival time for P3: 0
Burst time for P3: 7
Arrival time for P4: 0
Burst time for P4: 3
Process Arrival Time Burst Time Completion Time Turnaround Time Waiting Time Response Time
P1 0 6 9 9 3 3
P2 0 8 24 24 16 16
P3 0 7 16 16 9 9
P4 0 3 3 3 0 0

Average Turnaround
Time: 13.0
Average Waiting
Time: 7.0
Average Response
Time: 7.0
SJF PRE-EMPTIVE:
SOURCE CODE:
import matplotlib.pyplot as plt
def findWaitingTime(processes, n, wt, ct, gantt_chart):
rt = [0] * n
for i in range(n):
rt[i] = processes[i][2]
complete = 0
t = 0
min_rt = float('inf')
short = 0
check = False
while complete != n:
for j in range(n):
if processes[j][1] <= t and rt[j] < min_rt and rt[j] > 0:
min_rt = rt[j]
short = j
check = True
if not check:
t += 1
continue
rt[short] -= 1
min_rt = rt[short]
if min_rt == 0:
min_rt = float('inf')
complete += 1
check = False
ct[short] = t + 1
wt[short] = ct[short] - processes[short][1] -
processes[short][2]
if wt[short] < 0:
wt[short] = 0
gantt_chart.append((t, t + 1, processes[short][0]))
t += 1
def findTurnAroundTime(processes, n, wt, tat):
for i in range(n):
tat[i] = processes[i][2] + wt[i]
def findavgTime(processes, n):
wt = [0] * n
tat = [0] * n
ct = [0] * n
gantt_chart = []
findWaitingTime(processes, n, wt, ct, gantt_chart)
findTurnAroundTime(processes, n, wt, tat)
print("Processes\tArrival Time\tBurst Time\tCompletion Time\tWaiting
Time\tTurn-Around Time")
total_wt = 0
total_tat = 0
for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
print(f" {processes[i][0]}\t\t{processes[i][1]}\t\t{processes[i][
2]}\t\t{ct[i]}\t\t{wt[i]}\t\t{tat[i]}")
avg_wt = total_wt / n
avg_tat = total_tat / n
print(f"\nAverage Waiting Time: {avg_wt:.5f}")
print(f"Average Turnaround Time: {avg_tat:.5f}")
# Plot the Gantt chart
plot_gantt_chart(gantt_chart, n)
def plot_gantt_chart(gantt_chart, n):
fig, gnt = plt.subplots()
# Setting Y-axis limits
gnt.set_ylim(0, n + 1)
# Setting X-axis limits
gnt.set_xlim(0, gantt_chart[-1][1] + 1)
# Setting labels for x-axis and y-axis
gnt.set_xlabel('Time')
gnt.set_ylabel('Processes')
# Create a list of unique process numbers from the Gantt chart
unique_processes = list(set(process for _, _, process in gantt_chart))
unique_processes.sort()
# Setting ticks and labels for y-axis
gnt.set_yticks(unique_processes)
gnt.set_yticklabels([f'P{process}' for process in unique_processes])
# Plot Gantt chart bars
for i in range(len(gantt_chart)):
start, end, process = gantt_chart[i]
gnt.broken_barh([(start, end - start)], (process - 0.4, 0.8),
facecolors=('tab:blue', 'tab:orange', 'tab:green', 'tab:red')[process %
4])
plt.title('Gantt Chart')
plt.show()
def main():
n = int(input("Enter the number of processes: "))
processes = []
for i in range(n):
arrival_time = int(input(f"Enter arrival time for process {i + 1}:
"))
burst_time = int(input(f"Enter burst time for process {i + 1}: "))
processes.append([i + 1, arrival_time, burst_time])
processes.sort(key=lambda x: x[1]) # Sort by arrival time
findavgTime(processes, n)
main()

OUTPUT:
Enter the number of processes: 4
Enter arrival time for process 1: 0
Enter burst time for process 1: 8
Enter arrival time for process 2: 1
Enter burst time for process 2: 4
Enter arrival time for process 3: 2
Enter burst time for process 3: 9
Enter arrival time for process 4: 3
Enter burst time for process 4: 5
Processes Arrival Time Burst Time Completion Time Waiting Time Turn-Around Time Response Time
1 0 8 17 9 17 0
2 1 4 5 0 4 1
3 2 9 26 15 24 17
4 3 5 10 2 7 5

Average Waiting Time: 6.50000


Average Turnaround Time: 13.0000
Average Response Time: 5.75000

ROUND ROBIN
SOURCE CODE:
import matplotlib.pyplot as plt
def round_robin(processes, burst_time, arrival_time, quantum):
n = len(processes)
waiting_time = [0] * n
turnaround_time = [0] * n
response_time = [0] * n
remaining_time = burst_time.copy()
completion_time = [0] * n
time = 0
timeline = []
gantt_chart = []
while any(remaining_time):
for i in range(n):
if remaining_time[i] > 0 and arrival_time[i] <= time:
if remaining_time[i] > quantum:
timeline.append(processes[i])
gantt_chart.append(quantum)
time += quantum
remaining_time[i] -= quantum
else:
timeline.append(processes[i])
gantt_chart.append(remaining_time[i])
time += remaining_time[i]
completion_time[i] = time
waiting_time[i] = time - burst_time[i] -
arrival_time[i]
response_time[i] = quantum * i # Response time is
calculated as quantum * i
remaining_time[i] = 0
print("Process\tArrival Time\tBurst Time\tCompletion Time\tWaiting
Time\tTurnaround Time\tResponse Time") # Table headings
for i in range(n):
turnaround_time[i] = completion_time[i] - arrival_time[i]
print(f"{processes[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t
{completion_time[i]}\t\t{waiting_time[i]}\t\t{turnaround_time[i]}\t\t{resp
onse_time[i]}")
avg_waiting_time = sum(waiting_time) / n
avg_turnaround_time = sum(turnaround_time) / n
avg_response_time = sum(response_time) / n # Calculate average
response time
print(f"\nAverage Waiting Time: {avg_waiting_time:.2f}")
print(f"Average Turnaround Time: {avg_turnaround_time:.2f}")
print(f"Average Response Time: {avg_response_time:.2f}")
plt.bar(range(len(gantt_chart)), gantt_chart, tick_label=timeline)
plt.xlabel('Time')
plt.ylabel('Burst Time')
plt.title('Round Robin Gantt Chart')
plt.show()
n = int(input("Enter the number of processes: "))
processes = [f"P{i}" for i in range(n)]
arrival_time = [int(input(f"Enter arrival time for {processes[i]}: ")) for
i in range(n)]
burst_time = [int(input(f"Enter burst time for {processes[i]}: ")) for i
in range(n)]
quantum = int(input("Enter time quantum: "))
round_robin(processes, burst_time, arrival_time, quantum)
# Plot the graph for AWT vs. Time Quantum
quantum_values = list(range(1, 11))
avg_waiting_times = []
for quantum_value in quantum_values:
avg_waiting_time , _, _, _, _, _, _ = round_robin(processes, burst_time,
arrival_time, quantum_value)
avg_waiting_times.append(avg_waiting_time)
plt.figure(figsize=(8, 4))
plt.plot(quantum_values, avg_waiting_times, marker='o')
plt.xlabel('Time Quantum')
plt.ylabel('Average Waiting Time')
plt.title('Average Waiting Time (AWT) vs. Time Quantum')
plt.grid(True)
plt.show()
# Plot the graph for ATAT vs. Time Quantum
avg_turnaround_times = []
for quantum_value in quantum_values:
_, avg_turnaround_time, _, _, _, _, _ = round_robin(processes, burst_time,
arrival_time, quantum_value)
avg_turnaround_times.append(avg_turnaround_time)
plt.figure(figsize=(8, 4))
plt.plot(quantum_values, avg_turnaround_times, marker='x', color='orange')
plt.xlabel('Time Quantum')
plt.ylabel('Average Turnaround Time')
plt.title('Average Turnaround Time (ATAT) vs. Time Quantum')
plt.grid(True)
plt.show()

OUTPUT:
Enter the number of processes: 4
Enter arrival time for P0: 0
Enter arrival time for P1: 1
Enter arrival time for P2: 2
Enter arrival time for P3: 4
Enter burst time for P0: 10
Enter burst time for P1: 5
Enter burst time for P2: 1
Enter burst time for P3: 8
Enter time quantum: 2
Process Arrival Time Burst Time Completion Time Waiting Time Turnaround Time Response Time
P0 0 10 24 14 24 0
P1 1 5 16 10 15 2
P2 2 1 5 2 3 4
P3 4 8 22 10 18 6
Average Waiting Time: 9.00
Average Turnaround Time: 15.00
Average Response Time: 3.00

You might also like