Professional Documents
Culture Documents
4 - Part A
Aim: Study various Process Scheduling Algorithm and implement Shortest Job First algorithm for
scheduling 5 Processes. Also calculate the Average waiting time and average turnaround time for
the same.
Requirements: C Programming knowledge and understanding of CPU scheduling concept.
Outcome: Understand the CPU scheduling algorithm in an operating system.
Theory:
To calculate the average waiting time in the shortest job first algorithm the sorting of the process
based on their burst time in ascending order then calculate the waiting time of each process as the
sum of the bursting times of all the process previous or before to that process.
ALGORITHM:
1. Preemptive
def shortest_job_first_np(p):
start = []
end = []
spent_time = 0
p.sort(key=lambda x: x[1])
for i in range(len(p)):
temp0 = []
temp = []
temp2 = []
for j in range(len(p)):
if (p[j][1] <= spent_time) and (p[j][3] == 0):
temp.extend([p[j][0], p[j][1], p[j][2]])
temp0.append(temp)
temp = []
elif p[j][3] == 0:
temp.extend([p[j][0], p[j][1], p[j][2]])
temp2.append(temp)
temp = []
if len(temp0) != 0:
temp0.sort(key=lambda x: x[2])
start.append(spent_time)
st = spent_time
spent_time = spent_time + temp0[0][2]
e_time = spent_time
end.append(e_time)
for k in range(len(p)):
if p[k][0] == temp0[0][0]:
break
p[k][3] = 1
p[k].append(st)
p[k].append(e_time)
elif len(temp0) == 0:
if spent_time < temp2[0][1]:
spent_time = temp2[0][1]
start.append(spent_time)
spent_time = spent_time + temp2[0][2]
e_time = spent_time
end.append(e_time)
for k in range(len(p)):
if p[k][0] == temp2[0][0]:
break
p[k][3] = 1
p[k].append(e_time)
total_wt = 0
for i in range(len(p)):
wt = p[i][4] - p[i][1]
total_wt += wt
p[i].append(wt)
awt = total_wt / len(p)
total_tat = 0
for i in range(len(p)):
tat = p[i][5] - p[i][1]
total_tat += tat
p[i].append(tat)
atat = total_tat / len(p)
print("Process \tAT \t BT \t Start Time \tEnd Time \t\tWT \t\t TAT")
for i in range(len(p)):
for j in range(len(p[i])):
if j != 3:
print(p[i][j], end="\t\t\t")
print()
print("Average Waiting Time :", awt, "ms")
print("Average Turnaround Time :", atat, "ms")
processes = [["P1", 0, 3, 0], ["P2", 3, 2, 0], ["P3", 1, 4, 0], ["P4", 4, 3, 0], ["P5", 2, 5, 0]]
shortest_job_first_np(processes)
Output:
Questions:
1. Distinguish between Preemptive and Non Preemptive CPU scheduling?
2. What is turnaround time?