Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm

  • Difficulty Level : Medium
  • Last Updated : 10 May, 2022

In previous post, we have discussed Set 1 of SJF i.e. non-preemptive. In this post we will discuss the preemptive version of SJF known as Shortest Remaining Time First (SRTF).

In the Shortest Remaining Time First (SRTF) scheduling algorithm, the process with the smallest amount of time remaining until completion is selected to execute. Since the currently executing process is the one with the shortest amount of time remaining by definition, and since that time should only reduce as execution progresses, processes will always run until they complete or a new process is added that requires a smaller amount of time.

Examples to show working of Preemptive Shortest Job First CPU Scheduling Algorithm:

Example-1: Consider the following table of arrival time and burst time for five processes P1, P2, P3, P4 and P5

ProcessBurst TimeArrival Time
 P1   6 ms2 ms
 P2 2 ms5 ms
 P3 8 ms1 ms
 P4 3 ms0 ms
 P5 4 ms4 ms

The Shortest Job First CPU Scheduling Algorithm will work on the basis of steps as mentioned below:

At time = 0,

  • Process P4 arrives and starts executing
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
0-1msP40ms 1ms3ms2ms

At time= 1, 

  • Process P3 arrives. 
  • But, as P4 has a shorter burst time. It will continue execution.
  • Thus, P3 will wait till P4 gets executed.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
1-2msP40ms        P31ms2ms1ms
P31ms0ms8ms8ms

At time =2, 

  • Process P1 arrives with burst time = 6
  • As the burst time of P1 is more than that of P4 
  • Thus, P4 will continue its execution.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
2-3msP40ms      P3, P11ms1ms0ms
P31ms0ms8ms8ms
P12ms0ms6ms6ms

At time = 3, 

  • Process P4 will finish its execution. 
  • Then, the burst time of P3 and P1 is compared. 
  • Process P1 is executed because its burst time is less as compared to P3.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
3-4msP31ms

    

          P3

0ms8ms8ms
P12ms1ms6ms5ms

At time = 4, 

  • Process P5 arrives.
  • Then the burst time of P3, P5, and P1 is compared. 
  • Process P5 gets executed first among them because its burst time is lowest, and process P1 is preempted.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
4-5msP31ms       P3, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms1ms4ms3ms

At time = 5, 

  • Process P2 arrives.
  • The burst time of all processes are compared, 
  • Process P2 gets executed as its burst time is lowest among all. 
  • Process P5 is preempted.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
5-6msP31ms   P3, P5, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms0ms3ms3ms
P25ms1ms2ms1ms

At time = 6, 

  • Process P2 will keep executing.
  • It will execute till time = 8 as the burst time of P2 is 2ms
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
6-7msP31ms

P3, P5, P1

0ms8ms8ms
P12ms0ms5ms5ms
P54ms0ms3ms3ms
P25ms1ms1ms0ms

At time=7, 

  • The process P2 finishes its execution.
  • Then again the burst time of all remaining processes is compared. 
  • The Process P5 gets executed because its burst time is lesser than the others.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
7-10msP31msP3, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms3ms3ms0ms

At time = 10, 

  • The process P5 will finish its execution. 
  • Then the burst time of the remaining processes P1 and P3 is compared. 
  • Thus, process P1 is executed as its burst time is less than P3
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
10-15msP31ms        P30ms8ms8ms
P14ms4ms5ms0ms

At time = 15,

  • The process P1 finishes its execution and P3 is the only process left. 
  • P3 will start executing.
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
15-23msP31ms 8ms8ms0ms

At time = 23, 

  • Process P3 will finish its execution.
  • The overall execution of the processes will be as shown below:
Time InstanceProcessArrival TimeWaiting TableExecution TimeInitial Burst TimeRemaining Burst 
Time
0-1msP40ms 1ms3ms2ms
1-2msP40ms        P31ms2ms1ms
P31ms0ms8ms8ms
2-3msP40ms      P3, P11ms1ms0ms
P31ms0ms8ms8ms
P12ms0ms6ms6ms
3-4msP31ms

    

        P3

0ms8ms8ms
P12ms1ms6ms5ms
4-5msP31ms       P3, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms1ms4ms3ms
5-6msP31ms   P3, P5, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms0ms3ms3ms
P25ms1ms2ms1ms
6-7msP31ms   P3, P5, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms0ms3ms3ms
P25ms1ms1ms0ms
7-10msP31ms   P3, P10ms8ms8ms
P12ms0ms5ms5ms
P54ms3ms3ms0ms
10-15msP31ms        P30ms8ms8ms
P14ms4ms5ms0ms
15-23msP31ms 8ms8ms0ms

Gantt chart for above execution:

Gantt chart for SRTF

Now, lets calculate average

Process  Completion Time Turn Around Time Waiting Time
 P1  1515-2 = 1313-6 = 7
 P277-5 = 22-2 = 0
 P32323-1 = 2222-8 = 14
 P433-0 = 33-3 = 0
 P51010-4 = 66-4 = 2

Now, 

Implementation of SRTF Algorithm: 

Approach:

 Program to implement Shortest Remaining Time First:

C++




// C++ program to implement Shortest Remaining Time First
// Shortest Remaining Time First (SRTF)
  
#include <bits/stdc++.h>
using namespace std;
  
struct Process {
    int pid; // Process ID
    int bt; // Burst Time
    int art; // Arrival Time
};
  
// Function to find the waiting time for all
// processes
void findWaitingTime(Process proc[], int n,
                                int wt[])
{
    int rt[n];
  
    // Copy the burst time into rt[]
    for (int i = 0; i < n; i++)
        rt[i] = proc[i].bt;
  
    int complete = 0, t = 0, minm = INT_MAX;
    int shortest = 0, finish_time;
    bool check = false;
  
    // Process until all processes gets
    // completed
    while (complete != n) {
  
        // Find process with minimum
        // remaining time among the
        // processes that arrives till the
        // current time`
        for (int j = 0; j < n; j++) {
            if ((proc[j].art <= t) &&
            (rt[j] < minm) && rt[j] > 0) {
                minm = rt[j];
                shortest = j;
                check = true;
            }
        }
  
        if (check == false) {
            t++;
            continue;
        }
  
        // Reduce remaining time by one
        rt[shortest]--;
  
        // Update minimum
        minm = rt[shortest];
        if (minm == 0)
            minm = INT_MAX;
  
        // If a process gets completely
        // executed
        if (rt[shortest] == 0) {
  
            // Increment complete
            complete++;
            check = false;
  
            // Find finish time of current
            // process
            finish_time = t + 1;
  
            // Calculate waiting time
            wt[shortest] = finish_time -
                        proc[shortest].bt -
                        proc[shortest].art;
  
            if (wt[shortest] < 0)
                wt[shortest] = 0;
        }
        // Increment time
        t++;
    }
}
  
// Function to calculate turn around time
void findTurnAroundTime(Process proc[], int n,
                        int wt[], int tat[])
{
    // calculating turnaround time by adding
    // bt[i] + wt[i]
    for (int i = 0; i < n; i++)
        tat[i] = proc[i].bt + wt[i];
}
  
// Function to calculate average time
void findavgTime(Process proc[], int n)
{
    int wt[n], tat[n], total_wt = 0,
                    total_tat = 0;
  
    // Function to find waiting time of all
    // processes
    findWaitingTime(proc, n, wt);
  
    // Function to find turn around time for
    // all processes
    findTurnAroundTime(proc, n, wt, tat);
  
    // Display processes along with all
    // details
    cout << " P\t\t"
        << "BT\t\t"
        << "WT\t\t"
        << "TAT\t\t\n";
  
    // Calculate total waiting time and
    // total turnaround time
    for (int i = 0; i < n; i++) {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        cout << " " << proc[i].pid << "\t\t"
            << proc[i].bt << "\t\t " << wt[i]
            << "\t\t " << tat[i] << endl;
    }
  
    cout << "\nAverage waiting time = "
        << (float)total_wt / (float)n;
    cout << "\nAverage turn around time = "
        << (float)total_tat / (float)n;
}
  
// Driver code
int main()
{
    Process proc[] = { { 1, 6, 2 }, { 2, 2, 5 },
                    { 3, 8, 1 }, { 4, 3, 0}, {5, 4, 4} };
    int n = sizeof(proc) / sizeof(proc[0]);
  
    findavgTime(proc, n);
    return 0;
}

Java




// Java program to implement Shortest Remaining Time First
// Shortest Remaining Time First (SRTF)
  
class Process
{
    int pid; // Process ID
    int bt; // Burst Time
    int art; // Arrival Time
      
    public Process(int pid, int bt, int art)
    {
        this.pid = pid;
        this.bt = bt;
        this.art = art;
    }
}
  
public class GFG 
{
    // Method to find the waiting time for all
    // processes
    static void findWaitingTime(Process proc[], int n,
                                     int wt[])
    {
        int rt[] = new int[n];
       
        // Copy the burst time into rt[]
        for (int i = 0; i < n; i++)
            rt[i] = proc[i].bt;
       
        int complete = 0, t = 0, minm = Integer.MAX_VALUE;
        int shortest = 0, finish_time;
        boolean check = false;
       
        // Process until all processes gets
        // completed
        while (complete != n) {
       
            // Find process with minimum
            // remaining time among the
            // processes that arrives till the
            // current time`
            for (int j = 0; j < n; j++) 
            {
                if ((proc[j].art <= t) &&
                  (rt[j] < minm) && rt[j] > 0) {
                    minm = rt[j];
                    shortest = j;
                    check = true;
                }
            }
       
            if (check == false) {
                t++;
                continue;
            }
       
            // Reduce remaining time by one
            rt[shortest]--;
       
            // Update minimum
            minm = rt[shortest];
            if (minm == 0)
                minm = Integer.MAX_VALUE;
       
            // If a process gets completely
            // executed
            if (rt[shortest] == 0) {
       
                // Increment complete
                complete++;
                check = false;
       
                // Find finish time of current
                // process
                finish_time = t + 1;
       
                // Calculate waiting time
                wt[shortest] = finish_time -
                             proc[shortest].bt -
                             proc[shortest].art;
       
                if (wt[shortest] < 0)
                    wt[shortest] = 0;
            }
            // Increment time
            t++;
        }
    }
       
    // Method to calculate turn around time
    static void findTurnAroundTime(Process proc[], int n,
                            int wt[], int tat[])
    {
        // calculating turnaround time by adding
        // bt[i] + wt[i]
        for (int i = 0; i < n; i++)
            tat[i] = proc[i].bt + wt[i];
    }
       
    // Method to calculate average time
    static void findavgTime(Process proc[], int n)
    {
        int wt[] = new int[n], tat[] = new int[n];
        int  total_wt = 0, total_tat = 0;
       
        // Function to find waiting time of all
        // processes
        findWaitingTime(proc, n, wt);
       
        // Function to find turn around time for
        // all processes
        findTurnAroundTime(proc, n, wt, tat);
       
        // Display processes along with all
        // details
        System.out.println("Processes " +
                           " Burst time " +
                           " Waiting time " +
                           " Turn around time");
       
        // Calculate total waiting time and
        // total turnaround time
        for (int i = 0; i < n; i++) {
            total_wt = total_wt + wt[i];
            total_tat = total_tat + tat[i];
            System.out.println(" " + proc[i].pid + "\t\t"
                             + proc[i].bt + "\t\t " + wt[i]
                             + "\t\t" + tat[i]);
        }
       
        System.out.println("Average waiting time = " +
                          (float)total_wt / (float)n);
        System.out.println("Average turn around time = " +
                           (float)total_tat / (float)n);
    }
      
    // Driver Method
    public static void main(String[] args)
    {
         Process proc[] = { new Process(1, 6, 1), 
                            new Process(2, 8, 1),
                            new Process(3, 7, 2), 
                            new Process(4, 3, 3)};
          
         findavgTime(proc, proc.length);
    }
}

Python3




# Python3 program to implement Shortest Remaining Time First
# Shortest Remaining Time First (SRTF)
  
# Function to find the waiting time 
# for all processes 
def findWaitingTime(processes, n, wt): 
    rt = [0] * n
  
    # Copy the burst time into rt[] 
    for i in range(n): 
        rt[i] = processes[i][1]
    complete = 0
    t = 0
    minm = 999999999
    short = 0
    check = False
  
    # Process until all processes gets 
    # completed 
    while (complete != n):
          
        # Find process with minimum remaining 
        # time among the processes that 
        # arrives till the current time`
        for j in range(n):
            if ((processes[j][2] <= t) and 
                (rt[j] < minm) and rt[j] > 0):
                minm = rt[j]
                short = j
                check = True
        if (check == False):
            t += 1
            continue
              
        # Reduce remaining time by one 
        rt[short] -= 1
  
        # Update minimum 
        minm = rt[short] 
        if (minm == 0): 
            minm = 999999999
  
        # If a process gets completely 
        # executed 
        if (rt[short] == 0): 
  
            # Increment complete 
            complete += 1
            check = False
  
            # Find finish time of current 
            # process 
            fint = t + 1
  
            # Calculate waiting time 
            wt[short] = (fint - proc[short][1] -    
                                proc[short][2])
  
            if (wt[short] < 0):
                wt[short] = 0
          
        # Increment time 
        t += 1
  
# Function to calculate turn around time 
def findTurnAroundTime(processes, n, wt, tat): 
      
    # Calculating turnaround time 
    for i in range(n):
        tat[i] = processes[i][1] + wt[i] 
  
# Function to calculate average waiting 
# and turn-around times. 
def findavgTime(processes, n): 
    wt = [0] * n
    tat = [0] *
  
    # Function to find waiting time 
    # of all processes 
    findWaitingTime(processes, n, wt) 
  
    # Function to find turn around time
    # for all processes 
    findTurnAroundTime(processes, n, wt, tat) 
  
    # Display processes along with all details 
    print("Processes    Burst Time     Waiting"
                    "Time     Turn-Around Time")
    total_wt = 0
    total_tat = 0
    for i in range(n):
  
        total_wt = total_wt + wt[i] 
        total_tat = total_tat + tat[i] 
        print(" ", processes[i][0], "\t\t"
                   processes[i][1], "\t\t"
                   wt[i], "\t\t", tat[i])
  
    print("\nAverage waiting time = %.5f "%(total_wt /n) )
    print("Average turn around time = ", total_tat / n) 
      
# Driver code 
if __name__ =="__main__":
      
    # Process id's 
    proc = [[1, 6, 1], [2, 8, 1],
            [3, 7, 2], [4, 3, 3]]
    n = 4
    findavgTime(proc, n)
      
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)

C#




// C# program to implement Shortest Remaining Time First
// Shortest Remaining Time First (SRTF)
  
using System;
  
public class Process
{
    public int pid; // Process ID
    public int bt; // Burst Time
    public int art; // Arrival Time
      
    public Process(int pid, int bt, int art)
    {
        this.pid = pid;
        this.bt = bt;
        this.art = art;
    }
}
  
public class GFG 
{
    // Method to find the waiting 
    // time for all processes
    static void findWaitingTime(Process []proc, int n,
                                    int []wt)
    {
        int []rt = new int[n];
      
        // Copy the burst time into rt[]
        for (int i = 0; i < n; i++)
            rt[i] = proc[i].bt;
      
        int complete = 0, t = 0, minm = int.MaxValue;
        int shortest = 0, finish_time;
        bool check = false;
      
        // Process until all processes gets
        // completed
        while (complete != n) 
        {
      
            // Find process with minimum
            // remaining time among the
            // processes that arrives till the
            // current time`
            for (int j = 0; j < n; j++) 
            {
                if ((proc[j].art <= t) &&
                (rt[j] < minm) && rt[j] > 0) 
                {
                    minm = rt[j];
                    shortest = j;
                    check = true;
                }
            }
      
            if (check == false
            {
                t++;
                continue;
            }
      
            // Reduce remaining time by one
            rt[shortest]--;
      
            // Update minimum
            minm = rt[shortest];
            if (minm == 0)
                minm = int.MaxValue;
      
            // If a process gets completely
            // executed
            if (rt[shortest] == 0) 
            {
      
                // Increment complete
                complete++;
                check = false;
      
                // Find finish time of current
                // process
                finish_time = t + 1;
      
                // Calculate waiting time
                wt[shortest] = finish_time -
                            proc[shortest].bt -
                            proc[shortest].art;
      
                if (wt[shortest] < 0)
                    wt[shortest] = 0;
            }
            // Increment time
            t++;
        }
    }
      
    // Method to calculate turn around time
    static void findTurnAroundTime(Process []proc, int n,
                            int []wt, int []tat)
    {
        // calculating turnaround time by adding
        // bt[i] + wt[i]
        for (int i = 0; i < n; i++)
            tat[i] = proc[i].bt + wt[i];
    }
      
    // Method to calculate average time
    static void findavgTime(Process []proc, int n)
    {
        int []wt = new int[n];int []tat = new int[n];
        int total_wt = 0, total_tat = 0;
      
        // Function to find waiting time of all
        // processes
        findWaitingTime(proc, n, wt);
      
        // Function to find turn around time for
        // all processes
        findTurnAroundTime(proc, n, wt, tat);
      
        // Display processes along with all
        // details
        Console.WriteLine("Processes " +
                        " Burst time " +
                        " Waiting time " +
                        " Turn around time");
      
        // Calculate total waiting time and
        // total turnaround time
        for (int i = 0; i < n; i++) 
        {
            total_wt = total_wt + wt[i];
            total_tat = total_tat + tat[i];
            Console.WriteLine(" " + proc[i].pid + "\t\t"
                            + proc[i].bt + "\t\t " + wt[i]
                            + "\t\t" + tat[i]);
        }
      
        Console.WriteLine("Average waiting time = " +
                        (float)total_wt / (float)n);
        Console.WriteLine("Average turn around time = " +
                        (float)total_tat / (float)n);
    }
      
    // Driver Method
    public static void Main(String[] args)
    {
        Process []proc = { new Process(1, 6, 1), 
                            new Process(2, 8, 1),
                            new Process(3, 7, 2), 
                            new Process(4, 3, 3)};
          
        findavgTime(proc, proc.Length);
    }
}
  
// This code has been contributed by 29AjayKumar

Javascript




<script>
// Javascript program to implement 
// Shortest Remaining Time First
// Shortest Remaining Time First (SRTF)
  
class Process
{
    constructor(pid,bt,art)
    {
        this.pid = pid;    // Process ID
        this.bt = bt;    // Burst Time
        this.art = art;    // Arrival Time
    }
}
  
// Method to find the waiting time for all
    // processes
function findWaitingTime( proc,n,wt)
{
    let rt = new Array(n);
         
        // Copy the burst time into rt[]
        for (let i = 0; i < n; i++)
            rt[i] = proc[i].bt;
         
        let complete = 0, t = 0, minm = Number.MAX_VALUE;
        let shortest = 0, finish_time;
        let check = false;
         
        // Process until all processes gets
        // completed
        while (complete != n) {
         
            // Find process with minimum
            // remaining time among the
            // processes that arrives till the
            // current time`
            for (let j = 0; j < n; j++) 
            {
                if ((proc[j].art <= t) &&
                  (rt[j] < minm) && rt[j] > 0) {
                    minm = rt[j];
                    shortest = j;
                    check = true;
                }
            }
         
            if (check == false) {
                t++;
                continue;
            }
         
            // Reduce remaining time by one
            rt[shortest]--;
         
            // Update minimum
            minm = rt[shortest];
            if (minm == 0)
                minm = Number.MAX_VALUE;
         
            // If a process gets completely
            // executed
            if (rt[shortest] == 0) {
         
                // Increment complete
                complete++;
                check = false;
         
                // Find finish time of current
                // process
                finish_time = t + 1;
         
                // Calculate waiting time
                wt[shortest] = finish_time -
                             proc[shortest].bt -
                             proc[shortest].art;
         
                if (wt[shortest] < 0)
                    wt[shortest] = 0;
            }
            // Increment time
            t++;
        }
}
  
// Method to calculate turn around time
function findTurnAroundTime(proc,n,wt,tat)
{
     // calculating turnaround time by adding
        // bt[i] + wt[i]
        for (let i = 0; i < n; i++)
            tat[i] = proc[i].bt + wt[i];
}
  
// Method to calculate average time
function findavgTime(proc,n)
{
    let wt = new Array(n), tat = new Array(n);
        let  total_wt = 0, total_tat = 0;
         
        // Function to find waiting time of all
        // processes
        findWaitingTime(proc, n, wt);
         
        // Function to find turn around time for
        // all processes
        findTurnAroundTime(proc, n, wt, tat);
         
        // Display processes along with all
        // details
        document.write("Processes " +
                           " Burst time " +
                           " Waiting time " +
                           " Turn around time<br>");
         
        // Calculate total waiting time and
        // total turnaround time
        for (let i = 0; i < n; i++) {
            total_wt = total_wt + wt[i];
            total_tat = total_tat + tat[i];
            document.write(" " + proc[i].pid + 
            "      "
            + proc[i].bt + "    " + wt[i]
            + "    " + tat[i]+"<br>");
        }
         
        document.write("Average waiting time = " +
                          total_wt / n+"<br>");
        document.write("Average turn around time = " +
                           total_tat / n+"<br>");
}
  
// Driver Method
let proc=[new Process(1, 6, 1), 
                            new Process(2, 8, 1),
                            new Process(3, 7, 2), 
                            new Process(4, 3, 3)];
findavgTime(proc, proc.length);
  
  
// This code is contributed by rag2127
  
</script>

Time Complexity: O(N)
Auxiliary Space: O(1)

Advantages: 

Disadvantages: 

Source:Wiki
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!