ENع
→Scheduling metrics
الدرس 12 · CPU scheduling

Turnaround, response time and fairness

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

When several programs are ready to run and there is one CPU, the kernel's scheduler decides who runs next and for how long. Before comparing schedulers we need ways to score them. Run three 5-second jobs two ways, one after the other and then taking turns with a 1-second time slice, and watch three scores move in opposite directions: turnaround time, response time and fairness. Taking turns relies on the timer interrupt and the context switch, from the lesson "The context switch and the timer interrupt".

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 12 · تفاعلي
01 / 10

Three jobs, one CPU

Three jobs, A, B and C, arrive together at time 0. Each needs 5 seconds of CPU. There is one CPU, so the scheduler, the part of the kernel that picks who runs next, must choose an order.

job   arrives   needs
A     t = 0     5 s of CPU
B     t = 0     5 s of CPU
C     t = 0     5 s of CPU

total work    15 s on one CPU
the question  who runs next, and for how long?
to compare answers we need scores (metrics)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Three jobs, one CPU

    Three jobs, A, B and C, arrive together at time 0. Each needs 5 seconds of CPU. There is one CPU, so the scheduler, the part of the kernel that picks who runs next, must choose an order.

    job   arrives   needs
    A     t = 0     5 s of CPU
    B     t = 0     5 s of CPU
    C     t = 0     5 s of CPU
    
    total work    15 s on one CPU
    the question  who runs next, and for how long?
    to compare answers we need scores (metrics)
  2. First in, first out

    The simplest order: first in, first out (FIFO). The job at the head of the queue runs to the end, then moves to Finished and the next starts. A runs from 0 to 5 seconds, B from 5 to 10, C from 10 to 15.

    FIFO: run the head of the queue to the end
    
    t   0    5    10   15
        AAAAABBBBBCCCCC
    
    A   first runs at 0   finishes at 5
    B   first runs at 5   finishes at 10
    C   first runs at 10   finishes at 15
  3. Score 1: turnaround time

    Turnaround time is finish minus arrival: how long a job spent in the system. A took 5 seconds, B 10, C 15. The average is 10 seconds. Lower is better.

    turnaround = finish - arrival
    
    A   5 - 0 = 5 s
    B   10 - 0 = 10 s
    C   15 - 0 = 15 s
    average   (5 + 10 + 15) / 3 = 10 s
    
    measuring one real turnaround in C (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <time.h>
    #include <unistd.h>
    
    static double now(void) {
        struct timespec t;
        clock_gettime(CLOCK_MONOTONIC, &t);
        return t.tv_sec + t.tv_nsec / 1e9;
    }
    
    int main(void) {
        double arrival = now();              /* the job arrives */
        pid_t pid = fork();
        if (pid < 0) { perror("fork"); return 1; }
        if (pid == 0) {                      /* child: the job */
            volatile unsigned long x = 0;
            for (unsigned long i = 0; i < 50000000UL; i++) x += i;
            _exit(0);
        }
        waitpid(pid, NULL, 0);               /* until it finishes */
        printf("turnaround: %.3f s\n", now() - arrival);
        return 0;
    }
  4. Score 2: response time

    Response time is first run minus arrival: how long a job waits before it gets the CPU at all. A waits 0 seconds, B 5, C 10. The average is 5 seconds. A person typing into C would wait 10 seconds.

    response = first_run - arrival
    
    A   0 - 0 = 0 s
    B   5 - 0 = 5 s
    C   10 - 0 = 10 s
    average   (0 + 5 + 10) / 3 = 5 s
    
    turnaround matters for batch work (when is it done?);
    response matters for people (when does it react?)
  5. Taking turns: the time slice

    Round robin lets jobs take turns. A timer interrupt ends each time slice, here 1 second. The kernel saves the running job (a context switch), puts it at the back of the queue and starts the job at the head.

    round robin, time slice = 1 s
    
    every slice:
      timer interrupt     the CPU traps into the kernel
      context switch      save the running job, load the next
      running job         goes to the back of the queue
    
    the slice is a multiple of the timer period
    (OSTEP: a 10 ms timer allows 10, 20, ... ms slices)
  6. Round robin, one second each

    Same three jobs, same 15 seconds of work. Now A runs 1 second, then B, then C, then A again, round and round. A finishes at 13 seconds, B at 14, C at 15, each moving to Finished.

    round robin, slice 1 s
    
    t   0    5    10   15
        ABCABCABCABCABC
    
    A   first runs at 0   finishes at 13
    B   first runs at 1   finishes at 14
    C   first runs at 2   finishes at 15
  7. Response time: much better

    Every job starts within 2 seconds: A at 0, B at 1, C at 2. Average response drops from 5 seconds to 1. A person typing into any of them would see it react quickly.

    response = first_run - arrival
    
    A   0 - 0 = 0 s
    B   1 - 0 = 1 s
    C   2 - 0 = 2 s
    average   (0 + 1 + 2) / 3 = 1 s
    
    FIFO 5 s  ->  round robin 1 s
  8. Turnaround time: worse

    But every job now finishes near the end: at 13, 14 and 15 seconds. Average turnaround rises from 10 seconds to 14. Taking turns stretched every job out.

    turnaround = finish - arrival
    
    A   13 - 0 = 13 s
    B   14 - 0 = 14 s
    C   15 - 0 = 15 s
    average   (13 + 14 + 15) / 3 = 14 s
    
    FIFO 10 s  ->  round robin 14 s
    OSTEP: "Pretty awful!"
  9. Score 3: fairness

    Fairness asks how evenly the CPU is shared over a short stretch. In the first 3 seconds FIFO gives A all 3 and B and C nothing. Round robin gives each job 1 second: a perfectly even share.

    CPU seconds in the first 3 s
    FIFO          A 3   B 0   C 0
    round robin   A 1   B 1   C 1
    
    Jain's fairness index  (sum x)^2 / (n * sum x^2)
    1 = perfectly even, 1/n = one job got it all
    FIFO          0.33
    round robin   1.00
    
    over all 15 s both give each job 5 s:
    fairness depends on the time scale
  10. No free lunch

    Being fair on a short time scale gives fast response but slow turnaround. Running jobs to the end does the opposite. No scheduler wins every score, so a system picks what matters most: batch work or people waiting.

                  turnaround   response   fair?
    FIFO          10 s         5 s        no
    round robin   14 s         1 s        yes
    
    the experiment as a Python simulation:
    
    def run(jobs, slice_):
        left = dict(jobs)            # job -> seconds of CPU still needed
        queue = list(jobs)           # all arrive at t = 0, A first
        t, first, done = 0, {}, {}
        while queue:
            j = queue.pop(0)         # the job at the head runs
            first.setdefault(j, t)   # its first run
            step = min(slice_, left[j])
            t += step
            left[j] -= step
            if left[j]:
                queue.append(j)      # slice used up: back of the queue
            else:
                done[j] = t          # finished
        n = len(jobs)
        return sum(done.values()) / n, sum(first.values()) / n
    
    jobs = {"A": 5, "B": 5, "C": 5}
    print("FIFO", run(jobs, float("inf")))   # (avg turnaround, avg response)
    print("RR  ", run(jobs, 1))
    
    prints:
    FIFO (10.0, 5.0)
    RR   (14.0, 1.0)

اختبار يتاح بعد الخطوة الأخيرة.