28.2. Diagnosing CPU and Scheduling Pressure

CPU problems look simple on a graph and complicated in reality. A CPU can be busy doing useful work, busy in the kernel on behalf of a device, waiting for a hypervisor to schedule it, or idle while a task waits for I/O. The counters separate those states, and the scheduler and cgroup controls decide which tasks get a chance to run.

28.2.1. Interpreting Utilization, Load Average, and Run Queues

Start with the number of CPUs and a known load. On perf1, two vCPUs are visible, and six CPU-bound workers create more runnable tasks than the machine can run at once. Start them as a transient unit so the load outlives the shell that launched it. The systemd-run options used in this chapter are:

Option Description
--unit=name Give the transient unit a predictable name.
--collect Remove the unit and its cgroup after it exits.
--uid=user Run the command as that user.
--property=NAME=VALUE Set a resource-control or scheduling property, such as CPUQuota=25%.
--wait Wait for the command to finish before returning.
$ sudo systemd-run --unit=cpu-overload --collect stress-ng --cpu 6 --timeout 60s --quiet
Running as unit: cpu-overload.service; invocation ID: 5a8800e6a7b04de796fcda35bbedaf27

systemd-run prints the unit name on standard error; the workload continues in the background. After the load has had time to affect the one-minute average:

$ cat /proc/loadavg
1.80 0.88 0.93 8/147 18599

The first three numbers are the one-, five-, and fifteen-minute load averages; 8/147 counts runnable tasks over all tasks, and the final number is the most recently created process ID. The load average is 1.80, but eight tasks are runnable (8/147). That gap is the point: load average is an exponentially smoothed count, so it lags behind a sudden burst. The run queue is visible directly:

$ vmstat 1 3
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 7  0      0 1224664  15776 572152   11  121  9606  4141  631    4  6  2 74 17  0  0
 7  0      0 1224376 15784 572140    0    0     0    48 1483 2251 100  0  0  0  0  0
 8  0      0 1224328 15784 572156    0    0     0     0  637  788 100  0  0  0  0  0

r is the number of runnable tasks; b is the number blocked in uninterruptible sleep. Seven or eight runnable tasks on two CPUs is oversubscription: each task gets a share of a CPU rather than a CPU of its own. The us column is at or near 100 percent, so the CPUs are not idle, but the queue length is what explains why individual work is slower. vmstat's first sample is again the since-boot average, so read the later lines.

The load average can also rise from tasks blocked on I/O, not only from CPU contention: Linux counts tasks in uninterruptible sleep as well as runnable ones. A b value greater than zero points to storage or memory waits rather than a CPU shortage. Section 28.4 follows that clue.

28.2.2. Separating User Time, System Time, Steal Time, and I/O Wait

mpstat shows the same interval broken down per CPU and per state. Selected output is shown; the per-CPU rows of the final average section are omitted:

$ sudo mpstat -P ALL 1 2
Linux 6.12.86+deb13-amd64 (perf1)   11/24/26    _x86_64_    (2 CPU)

00:32:40     CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
00:32:41     all  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
00:32:41       0  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00
00:32:41       1  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00

00:32:41     CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
00:32:42     all   99.50    0.00    0.00    0.00    0.00    0.00    0.50    0.00    0.00    0.00
00:32:42       0   99.00    0.00    0.00    0.00    0.00    0.00    1.00    0.00    0.00    0.00
00:32:42       1  100.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00

Average:     CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
Average:     all   99.75    0.00    0.00    0.00    0.00    0.00    0.25    0.00    0.00    0.00

%usr is time in user-space code, %sys is time in the kernel, %iowait is idle time during which at least one task waited for block I/O, %steal is time the hypervisor gave to another virtual machine, and %idle is genuinely available. The average shows that the load was almost entirely user-space CPU: 99.75 percent. The 0.25 percent steal is host scheduling delay, not work done for this guest. On a physical machine, a high steal value is not applicable; inside a virtual machine it is a concrete sign that the host is oversubscribed.

iowait needs care. It is measured only when the CPU is otherwise idle; a busy CPU with a deep disk queue can show low iowait while requests wait a long time. Use iostat and per-process I/O for that case rather than reading iowait as a complete measure of storage health. A high %sys value, by contrast, points to kernel work such as packet processing, filesystem metadata, or syscall-heavy code.

CPU accounting under load

Figure 28.3. Measured CPU-time distribution from the six-worker test. The run queue, not the idle percentage alone, shows that the machine is oversubscribed.

28.2.3. Per-Process and Per-Thread Measurements

System utilization says which state the CPUs are in; pidstat says who put them there. Selected output is shown: the six workers and two of their averages, with the other system processes and the second interval omitted:

$ sudo pidstat 1 2
Linux 6.12.86+deb13-amd64 (perf1)   11/24/26    _x86_64_    (2 CPU)

23:24:22      UID       PID    %usr %system  %guest   %wait    %CPU   CPU  Command
23:24:22        0     18556   31.68    0.00    0.00   67.33   31.68     0  stress-ng-cpu
23:24:22        0     18557   31.68    0.00    0.00   68.32   31.68     0  stress-ng-cpu
23:24:22        0     18558   34.65    0.00    0.00   65.35   34.65     1  stress-ng-cpu
23:24:22        0     18559   34.65    0.00    0.00   65.35   34.65     1  stress-ng-cpu
23:24:22        0     18560   31.68    0.00    0.00   67.33   31.68     0  stress-ng-cpu
23:24:22        0     18561   31.68    0.00    0.00   68.32   31.68     1  stress-ng-cpu

Average:        0     18556   32.34    0.00    0.00   67.16   32.34     -  stress-ng-cpu
Average:        0     18558   33.83    0.00    0.00   66.17   33.83     -  stress-ng-cpu

Each worker is using about one third of a CPU and waiting about two thirds of the time. The %wait column is the part that distinguishes "CPU-bound" from "CPU-starved": the tasks are runnable, but the scheduler cannot give them more CPU because other tasks are runnable too. ps can add thread detail:

$ sudo ps -T -p $(pgrep -x prometheus | head -1) -o pid,tid,psr,pcpu,comm
    PID     TID PSR %CPU COMMAND
  18299   18299   1  0.0 prometheus
  18299   18302   0  0.0 prometheus
  18299   18303   1  0.1 prometheus
  18299   18304   0  0.0 prometheus
  18299   18305   0  0.1 prometheus
  18299   18306   1  0.0 prometheus
  18299   18307   1  0.0 prometheus

TID is the thread ID, PSR is the CPU the thread last ran on, and the repeated rows are the process's threads. A multithreaded service can have one hot thread and several idle ones; a per-process total hides that, while pidstat -t -p PID and ps -T expose it. The ps options used here are:

Option Description
-T Show one line per thread.
-p PID Select the process.
-o pid,tid,psr,pcpu,comm Choose process ID, thread ID, last CPU, CPU percentage, and command.
-L Equivalent thread display for many ps invocations.

28.2.4. Pressure Stall Information and Cgroup Constraints

Run queue length is instantaneous. Pressure Stall Information (PSI) summarizes how much time tasks spent waiting for a resource over 10-, 60-, and 300-second windows:

$ cat /proc/pressure/cpu
some avg10=96.11 avg60=44.93 avg300=12.25 total=572479914
full avg10=0.00 avg60=0.00 avg300=0.00 total=0

some means at least one task was stalled; full means every task was stalled. Under CPU overload, some is high while full remains zero: there is always a runnable task, so the CPU is not completely unavailable, but tasks are waiting. PSI is the most direct saturation signal for CPU, memory, and I/O, and it is what a modern monitoring system should graph alongside utilization. The numbers are cumulative counters plus moving averages; the avg10 value is the one most useful for an incident.

A cgroup can impose a hard CPU ceiling even when the host has idle CPUs. Run one worker with a 25 percent quota:

$ sudo systemd-run --unit=cpu-quota --collect --property=CPUQuota=25% stress-ng --cpu 1 --timeout 30s --quiet
Running as unit: cpu-quota.service; invocation ID: 0fa3c1b21ce84973aa0f682f9f7bb422

Inspect the effective quota and the accounting:

$ sudo systemctl show -p CPUQuotaPerSecUSec cpu-quota.service
CPUQuotaPerSecUSec=250ms
$ sudo cat /sys/fs/cgroup/system.slice/cpu-quota.service/cpu.stat
usage_usec 3724342
user_usec 3691321
system_usec 33021
nice_usec 0
nr_periods 148
nr_throttled 148
throttled_usec 11012525
nr_bursts 0
burst_usec 0

The unit is allowed 250 ms of CPU per second, or 25 percent of one CPU. It was throttled in all 148 periods and accumulated about 11.0 seconds of throttled time. A service with this quota can be slow while the host graph shows idle capacity; the cgroup statistics identify the cause. CPUQuota is one of several systemd resource controls; AllowedCPUs restricts affinity, CPUWeight changes relative share under contention, and MemoryMax is used in Section 28.3.

28.2.5. Measuring Scheduler, CPU-Quota, and Affinity Changes Under Controlled Contention

Scheduler changes are easy to make and hard to measure. Use a fixed CPU-bound program with a deterministic loop, run it on one CPU, and compare the elapsed time under the same contention. The cpu-work.py program prints a checksum as well as the elapsed time so a truncated run is detectable:

#!/usr/bin/env python3
import sys
import time

loops = int(sys.argv[1]) if len(sys.argv) > 1 else 12000000
x = 1
start = time.monotonic()
for _ in range(loops):
    x = (x * 1103515245 + 12345) & 0x7FFFFFFF
print(f"loops={loops} checksum={x} elapsed={time.monotonic() - start:.3f}s")
$ taskset -c 0 python3 cpu-work.py 8000000
loops=8000000 checksum=159194625 elapsed=1.812s

Now pin a competing worker to the same CPU and repeat the measurement. The competitor is started as a transient unit with AllowedCPUs=0:

$ sudo systemd-run --unit=cpu-contend --collect -p AllowedCPUs=0 stress-ng --cpu 1 --timeout 90s --quiet
Running as unit: cpu-contend.service; invocation ID: 9de49e2640aa43128719b4f8d8248366
$ taskset -c 0 python3 cpu-work.py 8000000
loops=8000000 checksum=159194625 elapsed=3.334s

The same work takes 3.33 seconds instead of 1.81 seconds. Raising the priority with nice changes the CFS weight, and a real-time policy preempts the competitor entirely:

$ sudo nice -n -10 taskset -c 0 python3 /home/john/debian-handbook/performance/cpu-work.py 8000000
loops=8000000 checksum=159194625 elapsed=3.371s
$ sudo chrt -f 50 taskset -c 0 python3 /home/john/debian-handbook/performance/cpu-work.py 8000000
loops=8000000 checksum=159194625 elapsed=2.306s

The nice -n -10 run made no measurable difference in this trial, and the SCHED_FIFO run improved to 2.31 seconds - better than the contended 3.33, but still above the 1.81-second baseline. Neither result is a contradiction: CFS nice weights shift relative share under contention without guaranteeing a fixed slice, SCHED_FIFO preempts normal tasks but cannot remove host scheduling noise, and a single run of each configuration is weak evidence. SCHED_FIFO gives the task the CPU ahead of normal tasks, at the cost of potentially starving them; it is appropriate for a carefully bounded real-time workload, not as a general performance fix. The affinity of the competitor is visible directly:

$ sudo ps -o pid,psr,comm -C stress-ng-cpu
    PID PSR COMMAND
  18852   0 stress-ng-cpu

The options used in this subsection are:

Command and option Description
taskset -c 0 command Run the command only on CPU 0.
nice -n -10 command Raise CFS priority by ten nice levels; root may use negative values.
chrt -f 50 command Use the FIFO real-time scheduling class at priority 50.
ps -o psr Show the processor on which a task last ran.

For a software profile rather than a scheduling experiment, perf records where time is spent. Hardware performance counters are not exposed by every virtual CPU; on this guest the software events work:

$ sudo perf stat -e task-clock,context-switches,cpu-migrations,page-faults python3 /home/john/debian-handbook/performance/cpu-work.py 5000000
loops=5000000 checksum=360452801 elapsed=1.153s

 Performance counter stats for 'python3 /home/john/debian-handbook/performance/cpu-work.py 5000000':

           1147.33 msec task-clock                       #    0.982 CPUs utilized
               310      context-switches                 #  270.193 /sec
                 1      cpu-migrations                   #    0.872 /sec
               825      page-faults                      #  719.063 /sec

       1.168883944 seconds time elapsed
       1.135002000 seconds user
       0.011944000 seconds sys

task-clock is the CPU time consumed; nearly one CPU was used for the whole wall-clock interval. The context switches and page faults are small. Hardware events such as cycles, instructions, and branches may print <not supported> on a virtual CPU without a performance monitoring unit; use the software events or perf record -e cpu-clock in that case. Section 28.5 uses perf record to find hot functions.