SJF Scheduling in Python
implement SJF scheduling in python taking input from the user
Sure! Below is the Python code that implements Shortest Job First (SJF) scheduling algorithm. The
program takes input from the user for the number of processes, their burst times, and calculates the
average waiting time and turnaround time.
SJF Scheduling Algorithm Code
python
# Function to calculate waiting time of each process
def calculate_waiting_time(processes, burst_times, n):
waiting_times = [0] * n # Initialize waiting times with 0
# Sorting the burst times in ascending order and rearranging processes accordingly
sorted_processes = sorted(zip(processes, burst_times), key=lambda x: x[1])
for i in range(1, n):
waiting_times[i] = sorted_processes[i - 1][1] + waiting_times[i - 1]
return waiting_times, sorted_processes
# Function to calculate turnaround time for each process
def calculate_turnaround_time(sorted_processes, waiting_times, n):
turnaround_times = [0] * n
for i in range(n):
turnaround_times[i] = sorted_processes[i][1] + waiting_times[i]
return turnaround_times
# Function to calculate average waiting and turnaround times
def calculate_average_times(n, waiting_times, turnaround_times):
total_waiting_time = sum(waiting_times)
total_turnaround_time = sum(turnaround_times)
avg_waiting_time = total_waiting_time / n
avg_turnaround_time = total_turnaround_time / n
return avg_waiting_time, avg_turnaround_time
# Main function to simulate SJF Scheduling
def sjf_scheduling():
# Take input from the user
n = int(input("Enter the number of processes: "))
processes = []
burst_times = []
for i in range(n):
process_id = input(f"Enter Process {i + 1} ID: ")
burst_time = int(input(f"Enter the burst time for {process_id}: "))
processes.append(process_id)
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/10
burst_times.append(burst_time)
# Calculate waiting times
waiting_times, sorted_processes = calculate_waiting_time(processes, burst_times, n)
# Calculate turnaround times
turnaround_times = calculate_turnaround_time(sorted_processes, waiting_times, n)
# Calculate average waiting time and average turnaround time
avg_waiting_time, avg_turnaround_time = calculate_average_times(n, waiting_times,
turnaround_times)
# Display the results
print("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
print(f"{sorted_processes[i][0]}\t\t{sorted_processes[i]
[1]}\t\t{waiting_times[i]}\t\t{turnaround_times[i]}")
print(f"\nAverage Waiting Time: {avg_waiting_time:.2f}")
print(f"Average Turnaround Time: {avg_turnaround_time:.2f}")
# Execute the SJF Scheduling function
if __name__ == "__main__":
sjf_scheduling()
How it works:
1. Input: The user inputs the number of processes and their burst times.
2. Sorting: The processes are sorted by their burst times to implement SJF (Shortest Job First)
scheduling.
3. Waiting Time: The waiting time for each process is calculated by adding the burst times of the
previous processes.
4. Turnaround Time: Turnaround time is calculated by adding the burst time of the process to its
waiting time.
5. Average Time: The average waiting time and turnaround time are calculated and printed.
Sample Input and Output:
yaml
Enter the number of processes: 3
Enter Process 1 ID: P1
Enter the burst time for P1: 6
Enter Process 2 ID: P2
Enter the burst time for P2: 8
Enter Process 3 ID: P3
Enter the burst time for P3: 7
Process ID Burst Time Waiting Time Turnaround Time
P1 6 0 6
P3 7 6 13
P2 8 13 21
Average Waiting Time: 6.33
Average Turnaround Time: 13.33
Key Points:
The program works for non-preemptive SJF.
It takes input dynamically from the user for any number of processes.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/10
Sorting is done based on burst time, ensuring the shortest job gets executed first.
implement round robin
Here’s the Python implementation of Round Robin (RR) scheduling. This algorithm assigns a fixed
time quantum to each process and cycles through them until all processes are complete. The program
will take input from the user for the number of processes, their burst times, and the time quantum.
Round Robin Scheduling Algorithm
python
# Function to perform Round Robin Scheduling
def round_robin(processes, burst_times, time_quantum):
n = len(processes)
remaining_burst_times = burst_times[:] # Copy of burst times for remaining burst
times
waiting_times = [0] * n
turnaround_times = [0] * n
current_time = 0
completed = 0 # Number of processes that have completed
process_queue = [] # Queue for processes to execute
while completed < n:
for i in range(n):
if remaining_burst_times[i] > 0:
# Process executes for a time quantum or until completion
if remaining_burst_times[i] > time_quantum:
current_time += time_quantum
remaining_burst_times[i] -= time_quantum
else:
# Process finishes in this quantum
current_time += remaining_burst_times[i]
waiting_times[i] = current_time - burst_times[i]
remaining_burst_times[i] = 0
completed += 1
turnaround_times[i] = current_time
# Calculate the average waiting time and average turnaround time
avg_waiting_time = sum(waiting_times) / n
avg_turnaround_time = sum(turnaround_times) / n
return waiting_times, turnaround_times, avg_waiting_time, avg_turnaround_time
# Main function to take input and run Round Robin scheduling
def rr_scheduling():
# Take input from the user
n = int(input("Enter the number of processes: "))
processes = []
burst_times = []
for i in range(n):
process_id = input(f"Enter Process {i + 1} ID: ")
burst_time = int(input(f"Enter the burst time for {process_id}: "))
processes.append(process_id)
burst_times.append(burst_time)
time_quantum = int(input("Enter the time quantum: "))
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/10
# Perform Round Robin scheduling
waiting_times, turnaround_times, avg_waiting_time, avg_turnaround_time =
round_robin(processes, burst_times, time_quantum)
# Display the results
print("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
print(f"
{processes[i]}\t\t{burst_times[i]}\t\t{waiting_times[i]}\t\t{turnaround_times[i]}")
print(f"\nAverage Waiting Time: {avg_waiting_time:.2f}")
print(f"Average Turnaround Time: {avg_turnaround_time:.2f}")
# Execute the Round Robin Scheduling function
if __name__ == "__main__":
rr_scheduling()
How it works:
1. Input: The user inputs the number of processes, their burst times, and the time quantum.
2. Execution: Each process is executed for a time quantum. If a process's burst time is greater than
the quantum, the remaining burst time is reduced and it is revisited in the next round. If a
process's burst time is less than or equal to the quantum, it finishes in that round.
3. Waiting Time and Turnaround Time:
Waiting Time: Calculated as the time the process spends waiting in the queue until it
completes.
Turnaround Time: The total time taken from submission to completion.
4. Average Time: The program calculates and displays the average waiting time and average
turnaround time.
Sample Input and Output:
yaml
Enter the number of processes: 3
Enter Process 1 ID: P1
Enter the burst time for P1: 10
Enter Process 2 ID: P2
Enter the burst time for P2: 5
Enter Process 3 ID: P3
Enter the burst time for P3: 8
Enter the time quantum: 2
Process ID Burst Time Waiting Time Turnaround Time
P1 10 10 20
P2 5 6 11
P3 8 12 20
Average Waiting Time: 9.33
Average Turnaround Time: 17.00
Key Points:
The time quantum determines how long each process gets to execute before moving to the
next process in the queue.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/10
The algorithm handles the execution of processes in a cyclic manner, ensuring each process gets
a fair share of CPU time.
The program computes waiting time, turnaround time, and average times for all processes.
You can modify the number of processes, burst times, and time quantum to simulate different
scheduling scenarios.
implement FCFS
Here’s the Python implementation of First-Come, First-Served (FCFS) scheduling, which is one of the
simplest scheduling algorithms. In FCFS, processes are executed in the order they arrive. The program
will take input from the user for the number of processes, their burst times, and calculate the waiting
time, turnaround time, and average times.
FCFS Scheduling Algorithm Code
python
# Function to calculate waiting time for each process
def calculate_waiting_time_fcfs(processes, burst_times, n):
waiting_times = [0] * n # Initialize waiting times with 0
# Waiting time for first process is 0, calculate for others
for i in range(1, n):
waiting_times[i] = burst_times[i - 1] + waiting_times[i - 1]
return waiting_times
# Function to calculate turnaround time for each process
def calculate_turnaround_time_fcfs(burst_times, waiting_times, n):
turnaround_times = [0] * n
for i in range(n):
turnaround_times[i] = burst_times[i] + waiting_times[i]
return turnaround_times
# Function to calculate average waiting and turnaround times
def calculate_average_times_fcfs(n, waiting_times, turnaround_times):
total_waiting_time = sum(waiting_times)
total_turnaround_time = sum(turnaround_times)
avg_waiting_time = total_waiting_time / n
avg_turnaround_time = total_turnaround_time / n
return avg_waiting_time, avg_turnaround_time
# Main function to simulate FCFS Scheduling
def fcfs_scheduling():
# Take input from the user
n = int(input("Enter the number of processes: "))
processes = []
burst_times = []
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/10
for i in range(n):
process_id = input(f"Enter Process {i + 1} ID: ")
burst_time = int(input(f"Enter the burst time for {process_id}: "))
processes.append(process_id)
burst_times.append(burst_time)
# Calculate waiting times
waiting_times = calculate_waiting_time_fcfs(processes, burst_times, n)
# Calculate turnaround times
turnaround_times = calculate_turnaround_time_fcfs(burst_times, waiting_times, n)
# Calculate average waiting time and average turnaround time
avg_waiting_time, avg_turnaround_time = calculate_average_times_fcfs(n, waiting_times,
turnaround_times)
# Display the results
print("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
print(f"
{processes[i]}\t\t{burst_times[i]}\t\t{waiting_times[i]}\t\t{turnaround_times[i]}")
print(f"\nAverage Waiting Time: {avg_waiting_time:.2f}")
print(f"Average Turnaround Time: {avg_turnaround_time:.2f}")
# Execute the FCFS Scheduling function
if __name__ == "__main__":
fcfs_scheduling()
How it works:
1. Input: The user inputs the number of processes and their burst times.
2. Execution: Processes are executed in the order they arrive (First-Come, First-Served).
3. Waiting Time and Turnaround Time:
Waiting Time: The time a process spends waiting before it starts execution.
Turnaround Time: The total time from the submission of a process to its completion.
4. Average Time: The program calculates and displays the average waiting time and average
turnaround time.
Sample Input and Output:
yaml
Enter the number of processes: 3
Enter Process 1 ID: P1
Enter the burst time for P1: 6
Enter Process 2 ID: P2
Enter the burst time for P2: 8
Enter Process 3 ID: P3
Enter the burst time for P3: 7
Process ID Burst Time Waiting Time Turnaround Time
P1 6 0 6
P2 8 6 14
P3 7 14 21
Average Waiting Time: 6.67
Average Turnaround Time: 13.67
Key Points:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/10
The waiting time for the first process is always 0.
The turnaround time is the sum of the process's burst time and its waiting time.
The program calculates average waiting time and average turnaround time across all
processes.
This algorithm is simple but not always efficient, especially if shorter processes are stuck behind
longer ones, leading to the "convoy effect." You can experiment with different inputs to observe how it
behaves under different scenarios.
now write all the 3 codes in cpp
Below are the implementations of FCFS, Round Robin, and SJF scheduling algorithms in C++.
1. FCFS (First Come First Served) Scheduling in C++
cpp
#include <iostream>
#include <vector>
using namespace std;
void fcfs_scheduling() {
int n;
cout << "Enter the number of processes: ";
cin >> n;
vector<string> processes(n);
vector<int> burst_times(n), waiting_times(n, 0), turnaround_times(n);
for (int i = 0; i < n; i++) {
cout << "Enter Process " << i + 1 << " ID: ";
cin >> processes[i];
cout << "Enter the burst time for " << processes[i] << ": ";
cin >> burst_times[i];
}
// Calculate waiting time
for (int i = 1; i < n; i++) {
waiting_times[i] = waiting_times[i - 1] + burst_times[i - 1];
}
// Calculate turnaround time
for (int i = 0; i < n; i++) {
turnaround_times[i] = burst_times[i] + waiting_times[i];
}
// Calculate average waiting time and turnaround time
float avg_waiting_time = 0, avg_turnaround_time = 0;
for (int i = 0; i < n; i++) {
avg_waiting_time += waiting_times[i];
avg_turnaround_time += turnaround_times[i];
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
// Display the results
cout << "\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n";
for (int i = 0; i < n; i++) {
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/10
cout << processes[i] << "\t\t" << burst_times[i] << "\t\t" << waiting_times[i] <<
"\t\t" << turnaround_times[i] << "\n";
}
cout << "\nAverage Waiting Time: " << avg_waiting_time << endl;
cout << "Average Turnaround Time: " << avg_turnaround_time << endl;
}
int main() {
fcfs_scheduling();
return 0;
}
2. Round Robin Scheduling in C++
cpp
#include <iostream>
#include <vector>
using namespace std;
void round_robin_scheduling() {
int n, time_quantum;
cout << "Enter the number of processes: ";
cin >> n;
vector<string> processes(n);
vector<int> burst_times(n), remaining_burst_times(n), waiting_times(n, 0),
turnaround_times(n);
for (int i = 0; i < n; i++) {
cout << "Enter Process " << i + 1 << " ID: ";
cin >> processes[i];
cout << "Enter the burst time for " << processes[i] << ": ";
cin >> burst_times[i];
remaining_burst_times[i] = burst_times[i]; // Initialize remaining burst time
}
cout << "Enter the time quantum: ";
cin >> time_quantum;
int current_time = 0, completed = 0;
while (completed < n) {
for (int i = 0; i < n; i++) {
if (remaining_burst_times[i] > 0) {
if (remaining_burst_times[i] > time_quantum) {
current_time += time_quantum;
remaining_burst_times[i] -= time_quantum;
} else {
current_time += remaining_burst_times[i];
waiting_times[i] = current_time - burst_times[i];
remaining_burst_times[i] = 0;
completed++;
}
turnaround_times[i] = current_time;
}
}
}
// Calculate average waiting time and turnaround time
float avg_waiting_time = 0, avg_turnaround_time = 0;
for (int i = 0; i < n; i++) {
avg_waiting_time += waiting_times[i];
avg_turnaround_time += turnaround_times[i];
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
// Display the results
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/10
cout << "\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n";
for (int i = 0; i < n; i++) {
cout << processes[i] << "\t\t" << burst_times[i] << "\t\t" << waiting_times[i] <<
"\t\t" << turnaround_times[i] << "\n";
}
cout << "\nAverage Waiting Time: " << avg_waiting_time << endl;
cout << "Average Turnaround Time: " << avg_turnaround_time << endl;
}
int main() {
round_robin_scheduling();
return 0;
}
3. SJF (Shortest Job First) Scheduling in C++
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Process {
string id;
int burst_time;
int waiting_time;
int turnaround_time;
};
// Comparison function to sort based on burst time
bool compare_by_burst_time(Process a, Process b) {
return a.burst_time < b.burst_time;
}
void sjf_scheduling() {
int n;
cout << "Enter the number of processes: ";
cin >> n;
vector<Process> processes(n);
for (int i = 0; i < n; i++) {
cout << "Enter Process " << i + 1 << " ID: ";
cin >> processes[i].id;
cout << "Enter the burst time for " << processes[i].id << ": ";
cin >> processes[i].burst_time;
}
// Sort processes based on burst time
sort(processes.begin(), processes.end(), compare_by_burst_time);
// Calculate waiting time
processes[0].waiting_time = 0; // First process has no waiting time
for (int i = 1; i < n; i++) {
processes[i].waiting_time = processes[i - 1].waiting_time + processes[i -
1].burst_time;
}
// Calculate turnaround time
for (int i = 0; i < n; i++) {
processes[i].turnaround_time = processes[i].burst_time +
processes[i].waiting_time;
}
// Calculate average waiting time and turnaround time
float avg_waiting_time = 0, avg_turnaround_time = 0;
for (int i = 0; i < n; i++) {
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/10
avg_waiting_time += processes[i].waiting_time;
avg_turnaround_time += processes[i].turnaround_time;
}
avg_waiting_time /= n;
avg_turnaround_time /= n;
// Display the results
cout << "\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n";
for (int i = 0; i < n; i++) {
cout << processes[i].id << "\t\t" << processes[i].burst_time << "\t\t"
<< processes[i].waiting_time << "\t\t" << processes[i].turnaround_time <<
"\n";
}
cout << "\nAverage Waiting Time: " << avg_waiting_time << endl;
cout << "Average Turnaround Time: " << avg_turnaround_time << endl;
}
int main() {
sjf_scheduling();
return 0;
}
Key Points for Each Algorithm:
FCFS: First-Come-First-Served. Each process is executed in the order it arrives. Waiting time for
each process depends on the burst times of the previous processes.
Round Robin: Each process gets a fixed time quantum. If a process's burst time is greater than
the quantum, it continues in the next round.
SJF (Non-preemptive): The process with the shortest burst time is selected first. This is non-
preemptive, meaning once a process starts, it finishes.
You can copy and paste these codes into a C++ environment, compile, and run them. They allow user
input for processes, burst times, and other parameters where applicable.
ChatGPT can make mistakes. Check important info.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/10