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:

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).

  1. 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%.
  2. Virtual Runtime Tracking: As a process runs, CFS tracks its vruntime. The rate at which vruntime increases is inversely proportional to the task's weight:
    • A process with a negative nice value (high priority/high weight) accumulates vruntime slowly.
    • A process with a positive nice value (low priority/low weight) accumulates vruntime quickly.
  3. Task Selection: The scheduler always chooses the runnable task with the lowest vruntime to execute next. Because higher-priority tasks accumulate vruntime at 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.

Permissions and Security

To prevent resource abuse, the operating system enforces permission constraints on nice values: