Linux Nice Command and CPU Scheduling Priority
The nice command in Linux is a utility used to influence
the scheduling priority of processes managed by the operating system's
kernel. This article explores how niceness values translate into
scheduling weights, how the kernel's scheduler allocates CPU time based
on these values, and the rules governing priority adjustments for both
new and running processes.
Understanding the Nice Value Scale
In Linux, process priority is measured on a scale from -20 to 19, known as the "nice" value:
- -20: Highest scheduling priority (the process is "least nice" to other processes and requests maximum CPU time).
- 0: Default priority assigned to standard user processes.
- 19: Lowest scheduling priority (the process is "nicest" and readily yields CPU time to others).
How the Scheduler Interprets Niceness
Modern Linux systems primarily use the Completely Fair Scheduler
(CFS) for standard non-real-time tasks. The CFS does not assign fixed
time slices based on priority; instead, it aims to allocate CPU
proportions fairly using a metric called vruntime (virtual
runtime).
- Weight Mapping: The kernel maps each nice value to an internal weight. These weights follow a geometric progression where each step in the nice scale alters CPU allocation by roughly 10%.
- Virtual Runtime Tracking: As a process runs, CFS
tracks its
vruntime. The rate at whichvruntimeincreases is inversely proportional to the task's weight:- A process with a negative nice value (high
priority/high weight) accumulates
vruntimeslowly. - A process with a positive nice value (low
priority/low weight) accumulates
vruntimequickly.
- A process with a negative nice value (high
priority/high weight) accumulates
- Task Selection: The scheduler always chooses the
runnable task with the lowest
vruntimeto execute next. Because higher-priority tasks accumulatevruntimeat a slower rate, they are selected more frequently and receive a larger share of overall CPU cycles.
Using the nice
and renice Commands
The nice command sets the priority when starting a new
process, while renice adjusts an already running task.
- Starting a low-priority task:
nice -n 10 python script.py - Starting a high-priority task:
sudo nice -n -5 python script.py - Adjusting an existing process:
renice -n 15 -p 1234
Permissions and Security
To prevent resource abuse, the operating system enforces permission constraints on nice values:
- Unprivileged Users: Can only set positive nice values (0 to 19) and can only increase the niceness of their own processes (lowering their priority). Unprivileged users cannot lower a nice value once it has been raised.
- Root/Superuser: Can assign any value from -20 to 19, allowing processes to receive boosted priority over standard system tasks.