Linux Scheduling – How ‘Nice’ Works in the Kernel

linuxlinux-kernelnicescheduling

sched_setscheduler says :

All scheduling is preemptive: if a process with a higher static
priority becomes ready to run, the currently running process will be
preempted and returned to the wait list for its static priority
level.

while setpriority says

This causes very low nice values (+19) to truly
provide little CPU to a process whenever there is any other higher
priority load on the system, and makes high nice values (-20) deliver
most of the CPU to applications that require it

So, how is changing the nice value going to influence the execution of programs? Is it similar to RT scheduling (where a program with higher nice value is going to interrupt program with lower nice value)?


All information on internet is how to use nice, and how to change priority of a process. No link explains how exactly process with different priority works. I couldn't even find the source code.

Best Answer

The proportion of the processor time a particular process receives is determined by the relative difference in niceness between it and other runnable processes.

The Linux Completely Fair Scheduler (CFS) calculates a weight based on the niceness. The weight is roughly equivalent to 1024 / (1.25 ^ nice_value). As the nice value decreases the weight increases exponentially. The timeslice allocated for the process is proportional to the weight of the process divided by the total weight of all runnable processes. The implementation of the CFS is in kernel/sched/fair.c.

The CFS has a target latency for the scheduling duration. Smaller target latencies yield better interactivity, but as the target latency decreases, the switching overhead increases, thus decreasing the overall throughput.

Given for instance a target latency of 20 milliseconds and two runnable processes of equal niceness, then both processes will run for 10 milliseconds each before being pre-empted in favour of the the other process. If there are 10 processes of equal niceness, each runs for 2 milliseconds each.

Now consider two processes, one with a niceness of 0 (the default), the other with a niceness of 5. The proportional difference between the corresponding weights is roughly 1/3, meaning that the higher priority process receives a timeslice of approximately 15 milliseconds while the lower priority process receives a timeslice of 5 milliseconds.

Lastly consider two processes with the niceness values of 5 and 10 respectively. While the absolute niceness is larger in this case, the relative differences between the niceness values is the same as in the previous example, yielding an identical timeslice division.

Related Question