Day 4: CPU I – scheduler and saturation
Goal: understand how Linux distributes the CPU, measure waiting time in the run queue, interpret context switches and priorities, recognize CPU steal – and see why more threads are rarely faster · Duration: about 3 hours · Prerequisite: Days 0–3
Where we start
perf1 is quiet, no test services are running any more. You check this in two steps.
Is a stress-ng still running? pgrep -c
counts the processes with this name:
# on perf1
pgrep -c stress-ngExpected:
0
Is a service in a failed state?
# on perf1
systemctl list-units --failed --no-legendsystemctl list-units --failedlists services in a failed state.--no-legendleaves out header and footer lines so that only real matches remain.
Expected: no output. If a service shows up here,
clean up with sudo systemctl reset-failed.
Introduction
A CPU can only run one thread at a time. On every server, however, hundreds of threads want to compute – not all at the same time, but often more than there are CPUs. Who gets their turn when and for how long is decided by the kernel’s scheduler. It is the reason why a system can still run smoothly at 100 % utilization – and why at 100 % it suddenly becomes sluggish.
Today you watch the scheduler at work. You measure how long threads stand in the queue before they may compute, see how priorities distribute the time, and get to know a property of modern Linux systems that surprises many: systemd does not divide the CPU between processes but between services. A service with a hundred threads therefore does not automatically get a hundred times as much as one with one.
Finally it is about time your VM does not even use itself: steal – time the hypervisor gave to someone else.
Today you learn:
- how the scheduler distributes the CPU: run queue, time slices, weights, context switches,
- to measure the waiting time in the run queue with
runqlatand its length withrunqlen, - to tell voluntary and involuntary context switches per process apart
with
pidstat -w, - to read a process’s running and waiting time from
/proc/PID/schedstat, - to set priorities with
niceandreniceand to measure their effect, - how cgroups divide the CPU between services,
- to recognize and classify CPU steal,
- why more threads than CPUs do not increase throughput, but do increase latency.
Background
The picture for today: the checkouts in the supermarket
Imagine perf1 as a supermarket with four checkouts. Each checkout is a CPU, each customer with a shopping cart a thread that wants to compute.
- The line at the checkout is the run queue.
Whoever’s turn it is gets served; the others wait. How long they wait is
measured by
runqlat; how long the line is, byrunqlen. - A change at the checkout is a context switch. If a customer leaves because they still have to fetch something from the shelf, that is voluntary. If the cashier sends them away because the next ones are waiting too long, that is involuntary.
- nice is the loyalty card: whoever has a better card is served more often – but only if there is a line at all. At an empty checkout everybody is served immediately.
- cgroups are departments with fixed checkout shares: the bakery customers and the beverage customers each get half of the checkout time – no matter whether two or twenty people stand in the bakery line.
- Steal: the cashier is called away to another store every now and then. The checkout stands still although customers are waiting – and in your own store you see no reason for it.
- More shopping carts do not make any checkout faster. Four checkouts serve the same number of customers per hour whether ten or forty stand in line. Only the waiting gets longer.
The terms
| Term | Meaning | In the picture |
|---|---|---|
| run queue | list of a CPU’s threads that want to compute and are waiting | line at a checkout |
| context switch | the kernel changes the thread on a CPU | change at the checkout |
| voluntary / involuntary | thread gives up (waits for something) / is preempted | leaves by itself / is sent away |
| weight, nice | share of the CPU, set via nice −20 to 19 | loyalty card |
cgroup, cpu.weight |
group of processes with a common share | department with a checkout share |
| steal | time the hypervisor did not give the VM | cashier elsewhere |
Remember: Utilization means “all checkouts are working”. Saturation means “there is a line in front of the checkouts”. Only the line makes customers – and requests – slow.
Run queue and time slices
Every CPU has its own run queue: the list of threads that want to compute and are currently waiting. The scheduler picks the next one from it, lets it run for a while and then switches. This switch is called a context switch: the kernel saves the registers of the old thread, loads those of the new one and jumps into it. A switch costs microseconds – and in addition cold caches, because the new thread no longer finds its data in the CPU cache.
There are two kinds of context switches:
- voluntary: the thread gives up the CPU itself because it is waiting for something – the disk, the network, a lock, a timer. Many voluntary switches mean: the thread waits a lot.
- involuntary: the scheduler takes the CPU away from the thread because its time is up and another one is next. Many involuntary switches mean: CPU saturation. There is more work than CPUs.
Since kernel 6.6 Linux uses the EEVDF scheduler (Earliest Eligible Virtual Deadline First), which replaces the older CFS (Completely Fair Scheduler). Both pursue the same goal: every thread gets a fair share of the CPU, measured in virtual runtime. EEVDF also makes sure that threads that only want to compute briefly do not have to wait long. For the measurements in this course the difference matters little; what matters is the principle of fairness.
So that the load is spread across all CPUs, the scheduler regularly moves threads between the run queues (load balancing). A thread that moves from CPU 2 to CPU 3 does not take its cache along – that costs too.
Weights and nice
“Fair” does not mean “equal”. Every thread has a weight, and the share of the CPU is proportional to the weight. You set the weight via the nice value: from −20 (highest priority) to 19 (lowest), default 0. The name comes from the fact that a process with a high nice value is “nice” to the others.
The weights are chosen so that each nice step makes a difference of about 10 % in CPU share. nice 0 has the weight 1024, nice 19 only 15. If two threads compete on one CPU, the one with nice 0 thus gets 1024 ÷ (1024 + 15) = 98.6 % of the time. nice only has an effect when there is competition: on a free CPU even a thread with nice 19 computes at full speed.
Only root may lower the nice value (raise the priority); anyone may raise it for their own processes.
cgroups divide the CPU between services
On a modern Linux with systemd there is a second level of fairness.
systemd puts every service into a cgroup of its own and switches on the
cpu controller. Every cgroup has a weight
(cpu.weight, default 100), and the scheduler distributes
the CPU first between the cgroups and only then between
the threads inside them.
The consequence: a service with 16 computing threads and your
terminal with one program do not share the CPU 16 to 1, but roughly
according to the weights of their cgroups. The system services
(system.slice) and the logged-in users
(user.slice) each have the weight 100. A service that goes
haywire therefore cannot paralyze the whole machine – it mainly slows
down itself. Drill 4 shows this, and it has an important consequence for
troubleshooting: a high load does not say who is suffering from
it.
CPU steal
In a VM, the CPUs you see are virtual CPUs. The hypervisor maps them onto real CPUs of the host. If the host has handed out more virtual CPUs than it has real ones (overcommitment), and all of them want to compute at the same time, it has to serve them in turn. The time in which your virtual CPU wanted to compute but got no real one is reported by the hypervisor to the VM’s kernel, which books it as steal.
Steal is invisible to the VM: programs simply run more slowly without
anything standing out in the VM – except the st column in
vmstat and %steal in mpstat.
Steal cannot be fixed inside the VM; you can only measure it and show it
to the operator of the host. With rented virtual servers, permanent
steal above a few percent is a sign of an overcommitted host.
More threads, more throughput?
A common reflex with slow services: more worker threads. That helps as long as the threads wait a lot – for the network, the disk, a database. Then another can compute while one waits. But if the threads only compute, and there are already as many as CPUs, additional threads bring no additional throughput. They share the same CPUs, every single job takes longer, and context switches are added. That is Little’s Law from Day 1 again: throughput stays the same, so with more parallelism latency has to rise. The diagnosis task measures exactly that.
Drill 1: Waiting time and length of the run queue
Where you are: on perf1.
What you have afterwards: two histograms of the run queue waiting time – quiet and saturated – and the length of the queue.
Step 1 – Quiet. How long do threads wait when there is no line?
# on perf1
sudo runqlat-bpfcc -m 5 1- You know
runqlatfrom Day 0. -mprints the times in milliseconds instead of microseconds.5 1measures for five seconds, once.
Expected (the last lines):
msecs : count distribution
0 -> 1 : 167 |****************************************|
2 -> 3 : 1 | |
In five seconds 168 threads were woken up; almost all waited less than a millisecond until they could compute. This is what a checkout without a line looks like.
Step 2 – Create load. Start eight computing workers on four CPUs as a user service so that they keep running even if you do something else in between:
# on perf1
systemd-run --user --unit=acht stress-ng --cpu 8 --timeout 90ssystemd-run --userstarts the command as a transient service of your user.--unit=achtgives it the nameacht.service(“eight”).stress-ng --cpu 8 --timeout 90s: eight workers that only compute for 90 seconds.
Step 3 – Measure saturated. Wait about eight seconds until all workers are running, then:
# on perf1
sudo runqlat-bpfcc -m 5 1Expected:
msecs : count distribution
0 -> 1 : 216 |* |
2 -> 3 : 6271 |****************************************|
4 -> 7 : 122 | |
8 -> 15 : 55 | |
The picture has shifted: most waiting times are now at 2 to 3 ms, some up to 15 ms. And the number of events has risen from 168 to over 6,600 – with eight threads on four CPUs the scheduler switches constantly. 3 ms of waiting sounds like little. For a service that is supposed to answer a request in 1 ms, it is three times its actual work – and it is added at every wakeup.
Step 4 – Length of the queue.
# on perf1
sudo runqlen-bpfcc 5 1runqlenlooks at every CPU 99 times per second and counts how many threads are waiting in its run queue – not counting the one currently running.5 1again means five seconds, one output.
Expected:
runqlen : count distribution
0 : 718 |*********************** |
1 : 1242 |****************************************|
2 : 20 | |
Mostly one thread per CPU is waiting – exactly what you expect with eight threads on four CPUs: one runs, one waits. If there are permanently more here, the CPU is more heavily overcommitted.
Remember:
runqlatmeasures how long you stand in line,runqlenhow long the line is. Without a line almost everything is below 1 ms.
If it doesn’t work
Failed to start transient service unit: Unit acht.service was already loaded: an earlier run is still known.systemctl --user reset-failed achtand try again.- The histogram looks like the quiet state: the 90 seconds are up. Start Step 2 again.
Save your progress? Sign up for free
Drill 2: Context switches and waiting time per process
Where you are: on perf1, the service
achtis still running (otherwise restart it as in Drill 1).What you have afterwards: measured for each worker how often the CPU is taken away from it and how much time it spends waiting instead of computing.
Step 1 – Context switches per process.
# on perf1
pidstat -w 1 1pidstat -wshows the context switches per process instead of CPU usage.1 1measures one second, once.
Expected (excerpt – the header line and the lines
with stress-ng-cpu):
23:07:47 UID PID cswch/s nvcswch/s Command
23:07:49 1000 75018 0.00 165.05 stress-ng-cpu
23:07:49 1000 75019 0.00 167.96 stress-ng-cpu
23:07:49 1000 75020 0.00 163.11 stress-ng-cpu
23:07:49 1000 75021 0.00 166.02 stress-ng-cpu
23:07:49 1000 75022 0.00 165.05 stress-ng-cpu
23:07:49 1000 75023 0.00 164.08 stress-ng-cpu
23:07:49 1000 75024 0.00 165.05 stress-ng-cpu
23:07:49 1000 75025 0.00 166.02 stress-ng-cpu
| Column | Value | Meaning |
|---|---|---|
cswch/s |
0 | voluntary switches per second – the workers wait for nothing, they only compute |
nvcswch/s |
~165 | involuntary switches: every 6 ms the scheduler takes the CPU away from each of them |
The nvcswch/s column is the most direct sign of CPU
saturation per process. Compare with dd from Day 3: there
it was thousands of voluntary and only 4 involuntary switches – the
opposite picture of a waiting process.
Step 2 – Pick a worker. pgrep -n names
the PID of the newest process with this name:
# on perf1
pgrep -n stress-ng-cpuExpected:
75025
Yours shows a different number. Put it in the next commands instead
of PID.
Step 3 – Running and waiting time. For every process the kernel keeps exact books on how long it computed and how long it waited:
# on perf1
cat /proc/PID/schedstatWait one second and run the same command again.
Expected (two calls, one second apart):
5126911690 5167836479 1726
5588779957 5710972264 1880
| Field | Meaning |
|---|---|
| 1 | compute time in nanoseconds |
| 2 | waiting time in the run queue in nanoseconds |
| 3 | number of time slices the process received |
The difference over one second:
- computed: 5,588,779,957 − 5,126,911,690 = 462 million ns = 0.46 s,
- waited: 5,710,972,264 − 5,167,836,479 = 543 million ns = 0.54 s,
- time slices: 154.
The worker spends a little more than half of the time waiting in the
run queue. That is saturation, measured for a single process – and the
source of the %wait column in pidstat.
Step 4 – The long version.
/proc/PID/sched is a detailed version with dozens of
fields. grep -E with four patterns separated by
| extracts only the four lines you need:
# on perf1
grep -E "nr_switches|nr_voluntary_switches|nr_involuntary_switches|se.load.weight" /proc/PID/schedExpected:
nr_switches : 1880
nr_voluntary_switches : 4
nr_involuntary_switches : 1876
se.load.weight : 1048576
Almost all switches are involuntary. se.load.weight is
the weight of the thread: 1024 for nice 0, internally multiplied by 1024
so that the kernel can calculate without fractions – 1024 × 1024 =
1,048,576.
Step 5 – Clean up.
# on perf1
systemctl --user stop achtRemember: Many involuntary switches = the process is preempted, the CPU is saturated. Many voluntary ones = the process is waiting for something else.
Save your progress? Sign up for free
Drill 3: Priorities with nice
Where you are: on perf1.
What you have afterwards: measured how the scheduler divides the CPU between two groups with different priorities.
Step 1 – The normal group. Four workers with normal priority:
# on perf1
systemd-run --user --unit=vorne stress-ng --cpu 4 --timeout 60sStep 2 – The “nice” group. Four workers with nice 19:
# on perf1
systemd-run --user --unit=hinten nice -n 19 stress-ng --cpu 4 --timeout 60snice -n 19 COMMANDstarts the command with nice value 19.
Step 3 – Take a look. Wait about eight seconds, then:
# on perf1
ps -o pid,ni,pri,psr,comm -C stress-ng-cpu-C stress-ng-cpuselects processes by name.-osets the columns:niis the nice value,prithe priority derived from it inps’s way of counting (higher = more important),psrthe CPU the process last ran on.
Expected:
PID NI PRI PSR COMMAND
174859 0 19 3 stress-ng-cpu
174860 0 19 0 stress-ng-cpu
174861 0 19 3 stress-ng-cpu
174862 0 19 1 stress-ng-cpu
174863 19 0 1 stress-ng-cpu
174864 19 0 0 stress-ng-cpu
174865 19 0 3 stress-ng-cpu
174866 19 0 3 stress-ng-cpu
Step 4 – Measure the distribution.
# on perf1
pidstat -u 2 1-uCPU values,2 1once over two seconds.
Expected (excerpt – the header line and the lines
with stress-ng-cpu):
12:43:48 UID PID %usr %system %guest %wait %CPU CPU Command
12:43:50 1000 174859 98.04 0.00 0.00 1.96 98.04 3 stress-ng-cpu
12:43:50 1000 174860 98.04 0.00 0.00 1.47 98.04 0 stress-ng-cpu
12:43:50 1000 174861 97.06 0.00 0.00 2.45 97.06 2 stress-ng-cpu
12:43:50 1000 174862 98.04 0.00 0.00 1.47 98.04 1 stress-ng-cpu
12:43:50 1000 174863 1.47 0.00 0.00 100.49 1.47 1 stress-ng-cpu
12:43:50 1000 174864 1.47 0.00 0.00 100.98 1.47 3 stress-ng-cpu
12:43:50 1000 174865 1.47 0.00 0.00 90.20 1.47 0 stress-ng-cpu
12:43:50 1000 174866 1.47 0.00 0.00 90.69 1.47 2 stress-ng-cpu
The four normal workers get 98 % each, the four “nice” ones 1.5 %
each – almost exactly the calculation from the Background section (98.6
to 1.4). The nice ones wait almost all the time (%wait
around 100; values just above 100 are rounding errors of pidstat). That
is the point of nice: background work such as backups or indexing runs
may compute when there is room and steps back as soon as something more
important comes along.
Step 5 – Look up the weight. Take the PID of a
worker with NI 19 from Step 3:
# on perf1
grep se.load.weight /proc/PID/schedExpected:
se.load.weight : 15360
15 × 1024 = 15,360 – the weight for nice 19.
Step 6 – Clean up.
# on perf1
systemctl --user stop vorne hintenRemember: nice is a loyalty card, not a brake: it only decides who is served first when there is a line.
Save your progress? Sign up for free
Drill 4: Who suffers under load? cgroups and fairness
Where you are: on perf1.
What you have afterwards: measured that a service with 16 computing threads hardly slows down a program in your session – but slows down the same program in its own cgroup a lot.
Your measuring instrument is a small Python program that counts to
ten million. It only computes, and time measures how long
it takes.
Step 1 – Without load.
# on perf1
time python3 -c "sum(range(10**7))"python3 -c "…"runs the Python code in the quotes:range(10**7)are the numbers from 0 to 9,999,999,sumadds them up.timein front of a command measures its running time.
Expected:
real 0m0.464s
user 0m0.456s
sys 0m0.008s
real is the wall-clock time, user the
compute time in program code, sys the time in the kernel.
Almost the whole time is spent computing: just under half a second.
Step 2 – A service with 16 computing threads.
# on perf1
sudo systemd-run --unit=bildwandler stress-ng --cpu 16 --timeout 600ssudo systemd-runwithout--usercreates a system service insystem.slice.
Step 3 – Measure. Wait about ten seconds. Then first the load:
# on perf1
uptimeExpected:
12:44:21 up 2 days, 3:18, 1 user, load average: 7.35, 3.58, 2.03
The load rises towards 16, on four CPUs. Now your program:
# on perf1
time python3 -c "sum(range(10**7))"Expected:
real 0m0.559s
user 0m0.510s
sys 0m0.027s
Your program takes only a good 20 % longer instead of five times as
long. The reason is in the Background section: your terminal lives in
user.slice, the service in system.slice, and
both have the same weight.
Step 4 – Check the weights. Is the cpu
controller switched on for the services?
# on perf1
cat /sys/fs/cgroup/system.slice/cgroup.subtree_controlExpected:
cpuset cpu io memory pids
cgroup.subtree_control shows which controllers are
switched on for the child cgroups – cpu is among them. Now
the two weights:
# on perf1
cat /sys/fs/cgroup/user.slice/cpu.weight# on perf1
cat /sys/fs/cgroup/system.slice/cpu.weightExpected: twice
100
Both halves weigh the same. The service with its 16 threads mainly competes with itself.
Step 5 – The same program in the same cgroup. Now the Python program is to run in the same service as the load. First stop the image converter:
# on perf1
sudo systemctl stop bildwandler# on perf1
sudo systemctl reset-failed bildwandlerSo that load and measurement run in the same service, you write them into a small script:
# on perf1
mkdir -p ~/tag04# on perf1
nano ~/tag04/gemeinsam.sh# Last und Messung in derselben cgroup (Tag 4, Drill 4)
stress-ng --cpu 16 --timeout 30s > /dev/null 2>&1 &
sleep 8
/usr/bin/time -f "real %e s" python3 -c "sum(range(10**7))"
wait| Line | Meaning |
|---|---|
stress-ng … & |
start the load in the background;
> /dev/null 2>&1 discards its output |
sleep 8 |
wait until all 16 workers are computing |
/usr/bin/time -f "real %e s" … |
the standalone program time; %e is the
elapsed time |
wait |
wait for the load to end |
The whole sequence of commands runs as one service, that is, in one cgroup. Start it:
# on perf1
sudo systemd-run --unit=gemeinsam --wait -q --pipe sh /home/ubuntu/tag04/gemeinsam.sh| Item | Meaning |
|---|---|
--unit=gemeinsam |
name of the service (“together”) |
--wait |
wait until the service has finished |
-q |
suppress the message “Running as unit” |
--pipe |
pass the service’s output to your terminal |
sh /home/ubuntu/tag04/gemeinsam.sh |
run the script; the full path, because the service does not start in your home directory |
Expected (after about 30 seconds):
real 1.74 s
1.74 seconds instead of 0.46 – almost four times as long. In the same cgroup the Python program is one of 17 threads sharing four CPUs, and it gets its fair share: roughly a quarter of a CPU.
Remember: High load does not say who suffers. Under systemd, the threads in the cgroup that creates the load suffer first. Whether your service is affected is shown by the PSI file of its cgroup (Day 3) and the
%waitof its processes.
If it doesn’t work
- Your program becomes much slower in Step 3: check
with
cat /sys/fs/cgroup/cgroup.subtree_controlwhethercpuis listed there. On systems without systemd or with the cpu controller switched off, this fairness does not exist, and all threads compete equally.
Save your progress? Sign up for free
Drill 5: CPU steal
Where you are: on perf1.
What you have afterwards: found steal in the recording and know how to recognize it in operations.
You can only create steal if the host is overcommitted. In the
author’s lab that did not work: the Proxmox host had enough real cores,
and even four computing threads in a second VM on the same host plus
four on perf1 left %steal at 0.15 %. That is the common
result in a well-dimensioned lab – and a good sign for the host.
sar’s recording (Day 2), however, sees what was going on in the days before. You search it for steal – day by day, by hand.
Step 1 – Which days are there?
# on perf1
ls /var/log/sysstat/Expected (in the lab on 30 November):
sa22
sa23
sa24
sa25
sa26
sa27
sa28
sa29
sa30
sar21
sar22
sar23
sar24
sar25
sar26
sar27
sar28
sar29
One file saNN per day (the measurements, NN = day of the
month) and, for completed days, one sarNN (a text summary).
You need the saNN files.
Step 2 – Go through one day. Take one file after the other, for example the 28th:
# on perf1
sar -u -f /var/log/sysstat/sa28-uCPU values,-f FILEfrom the recording instead of live.
Look in the %steal column for values above 5.
Expected (excerpt – the beginning of the output in the
author’s lab):
Linux 6.8.0-151-generic (cp1) 11/28/26 _x86_64_ (4 CPU)
00:00:10 CPU %user %nice %system %iowait %steal %idle
00:10:04 all 12.80 0.00 8.01 0.32 8.17 70.70
00:20:09 all 14.66 0.00 8.78 0.36 9.18 67.02
Further down come many lines of the same kind, for example these (excerpt):
01:20:10 all 17.11 0.00 10.02 0.49 9.66 62.73
01:50:01 all 15.64 0.00 9.63 0.45 10.22 64.06
03:10:01 all 14.19 0.00 9.05 0.42 9.81 66.52
03:20:10 all 13.68 0.00 8.99 0.40 9.40 67.53
07:10:10 all 14.28 0.00 9.23 0.41 9.63 66.46
The columns are in the header line: time, CPU, %user,
%nice, %system, %iowait,
%steal, %idle. In the night
before the 28th a lot was running at the same time on the author’s host,
and the VM got about 10 % steal – for hours. If you
find no values above 5 on any day, your VM never had significant
steal.
Step 3 – Look at the hour.
# on perf1
sar -u -f /var/log/sysstat/sa28 -s 01:00:00 -e 02:00:00-sand-elimit the output to a time window. Put in the day and time from your own finding.
Expected:
01:00:00 CPU %user %nice %system %iowait %steal %idle
01:10:10 all 17.91 0.00 11.26 0.48 9.29 61.06
01:20:10 all 17.11 0.00 10.02 0.49 9.66 62.73
01:30:01 all 20.46 0.00 10.22 0.43 9.25 59.64
01:40:10 all 16.54 0.00 9.88 0.46 9.06 64.06
01:50:01 all 15.64 0.00 9.63 0.45 10.22 64.06
Average: all 17.53 0.00 10.20 0.46 9.50 62.31
Read the lines like this: the VM wanted to compute about 37 % of the
time (%user + %system + %steal),
and of that it did not get a quarter. Every program in
the VM ran about a quarter more slowly in that hour than it would have
on a free host – without any reason being visible in the VM.
Steal can also come from I/O. During the diagnosis
task of Day 2, vmstat briefly showed 6 to 12 % in the
st column. The many small writes with flush loaded not only
the virtual disk but also the hypervisor processes serving it – on the
same real CPUs. So steal does not always mean “other VMs are computing”,
but “the host had no real CPU free for my virtual CPU at the
moment”.
Remember: Steal is the cashier helping out elsewhere: it cannot be fixed inside the VM, only measured –
stinvmstat,%stealinmpstatandsar.
Save your progress? Sign up for free
Diagnosis task
The team running the image converter reports: “Since yesterday every job takes about four times as long. And monitoring shows load 16 on perf1. We urgently need more CPUs.” Other teams on perf1 notice nothing.
Setup. The service simulates the image converter; each stress-ng worker stands for a worker thread converting images:
# on perf1
sudo systemd-run --unit=bildwandler stress-ng --cpu 16 --timeout 600s --metrics-brief--metrics-briefmakes stress-ng write a throughput summary at the end.
If systemd-run reports that the unit is already loaded,
reset it with sudo systemctl reset-failed bildwandler and
start again. Wait 20 seconds.
Task (20 minutes): is it true that perf1 needs more CPUs? Find out why the jobs take longer and propose a solution you can measure.
Solution path
Step 1 – The overview.
# on perf1
vmstat 1 3Expected:
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
r b swpd free buff cache si so bi bo in cs us sy id wa st gu
17 0 0 11671600 13768 287208 0 0 33 136 1862 4 4 1 93 0 1 0
16 0 0 11671600 13768 287208 0 0 0 0 4063 1327 100 0 0 0 0 0
16 0 0 11671600 13768 287208 0 0 0 0 4046 1391 100 0 0 0 0 0
r = 16 on four CPUs, us = 100,
b = 0, no I/O. Pure CPU saturation – this time the load is
right.
Step 2 – PSI confirms it.
# on perf1
cat /proc/pressure/cpuExpected:
some avg10=88.98 avg60=59.00 avg300=23.36 total=1772411563
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
Step 3 – How long do the threads wait?
# on perf1
sudo runqlat-bpfcc -m 5 1Expected:
msecs : count distribution
0 -> 1 : 202 |* |
2 -> 3 : 116 | |
4 -> 7 : 222 |* |
8 -> 15 : 6351 |****************************************|
16 -> 31 : 11 | |
32 -> 63 : 1 | |
8 to 15 ms at almost every wakeup – clearly more than the 2–3 ms with eight threads in Drill 1.
Step 4 – Who?
# on perf1
pidstat -u 1 1Expected (excerpt – header line and the first three workers):
12:44:35 UID PID %usr %system %guest %wait %CPU CPU Command
12:44:36 0 174942 24.27 0.00 0.00 73.79 24.27 0 stress-ng-cpu
12:44:36 0 174943 26.21 0.00 0.00 72.82 26.21 2 stress-ng-cpu
12:44:36 0 174944 24.27 0.00 0.00 75.73 24.27 0 stress-ng-cpu
Each worker computes only a quarter of the time and waits three quarters. There are 16 of them.
Step 5 – Which service do they belong to? The oldest
stress-ng process (the parent process) is found by
pgrep -o -x:
# on perf1
pgrep -o -x stress-ng-othe oldest match,-xthe name must be exactlystress-ng(notstress-ng-cpu).
Expected: a PID, in the lab 174939.
# on perf1
ps -o pid,cgroup:45,args -p 174939cgroup:45shows the cgroup in a 45-character-wide column,argsthe whole command line.
Expected:
PID CGROUP COMMAND
174939 0::/system.slice/bildwandler.service /usr/bin/stress-ng --cpu 16 --timeout 600s
Why do the others notice nothing? Because the service runs in its own cgroup and shares with the others by weight (Drill 4). It mainly slows down itself.
Step 6 – The core question: would more workers or more CPUs help? Measure the throughput – jobs per second – with 4 and with 16 workers. For this, stress-ng counts bogo ops (bogus operations), an artificial unit of work, ideal for comparison. First stop the service:
# on perf1
sudo systemctl stop bildwandler# on perf1
sudo systemctl reset-failed bildwandlerThen 20 seconds each with four and with sixteen workers:
# on perf1
stress-ng --cpu 4 --timeout 20s --metrics-briefExpected:
stress-ng: info: [75421] setting to a 20 secs run per stressor
stress-ng: info: [75421] dispatching hogs: 4 cpu
stress-ng: info: [75421] note: /proc/sys/kernel/sched_autogroup_enabled is 1 and this can impact scheduling throughput for processes not attached to a tty. Setting this to 0 may improve performance metrics
stress-ng: metrc: [75421] stressor bogo ops real time usr time sys time bogo ops/s bogo ops/s
stress-ng: metrc: [75421] (secs) (secs) (secs) (real time) (usr+sys time)
stress-ng: metrc: [75421] cpu 59616 20.00 79.91 0.06 2980.07 745.48
stress-ng: info: [75421] skipped: 0
stress-ng: info: [75421] passed: 4: cpu (4)
stress-ng: info: [75421] failed: 0
stress-ng: info: [75421] metrics untrustworthy: 0
stress-ng: info: [75421] successful run completed in 20.02 secs
Only the lines with metrc: matter; the hint about
sched_autogroup_enabled concerns processes without a
terminal and plays no role here.
# on perf1
stress-ng --cpu 16 --timeout 20s --metrics-briefExpected (excerpt – the lines with
metrc:):
stress-ng: metrc: [75484] stressor bogo ops real time usr time sys time bogo ops/s bogo ops/s
stress-ng: metrc: [75484] (secs) (secs) (secs) (real time) (usr+sys time)
stress-ng: metrc: [75484] cpu 58074 20.01 79.92 0.11 2902.50 725.71
The second-to-last column is the throughput per second of wall-clock time: 2,980 with four workers, 2,903 with sixteen. With four times as many workers the total throughput has not risen but dropped by almost 3 % (context switches, cold caches). Per worker this means: each one only manages a quarter – every single job takes four times as long. That is exactly what the team reported.
The answer to the ticket:
- More CPUs would help, but only because the service could then compute more – that would work just as well with four workers on more CPUs.
- The actual cause is the number of workers: 16 computing threads on 4 CPUs bring no throughput, only waiting time. Presumably someone increased the number of workers “yesterday”.
- Solution: as many computing workers as CPUs. For workers that wait a lot (network, disk) it may be more; for pure computing work it may not.
Step 7 – Fix.
# on perf1
sudo systemd-run --unit=bildwandler stress-ng --cpu 4 --timeout 120s --metrics-briefStep 8 – Check. Wait about ten seconds, then:
# on perf1
vmstat 1 2Expected (excerpt – the last line):
4 0 0 11723808 13848 287528 0 0 0 0 4130 60 100 0 0 0 0 0
# on perf1
sudo runqlat-bpfcc -m 5 1Expected (excerpt – the last lines):
msecs : count distribution
0 -> 1 : 292 |****************************************|
2 -> 3 : 2 | |
# on perf1
pidstat -u 1 1Expected (excerpt – the header line and the workers):
12:47:57 UID PID %usr %system %guest %wait %CPU CPU Command
12:47:58 0 175410 98.06 0.00 0.00 0.00 98.06 2 stress-ng-cpu
12:47:58 0 175411 98.06 0.00 0.00 0.00 98.06 1 stress-ng-cpu
12:47:58 0 175412 98.06 0.00 0.00 0.00 98.06 0 stress-ng-cpu
12:47:58 0 175413 97.09 0.00 0.00 0.97 97.09 3 stress-ng-cpu
r = 4, waiting time under 1 ms, %wait at 0,
every worker at 98 %. The CPU is still fully utilized – but no longer
saturated. The service manages the same amount, every job is four times
as fast, and the load alert disappears.
Step 9 – Clean up.
# on perf1
sudo systemctl stop bildwandler# on perf1
sudo systemctl reset-failed bildwandlerIf it doesn’t work
reset-failedreportsUnit bildwandler.service not loaded: the service ended cleanly and is already forgotten – not an error.- The throughput values vary strongly: something else
is running on your host right now (look at
%steal). Repeat the measurement twice and take the average.
Challenge
With the image converter running with 16 workers, lower the priority of all workers to nice 19 afterwards – with a single command, without restarting the service. Does that change anything about the workers’ waiting time? Why (not)?
Solution path:
First the PID of the stress-ng parent process, as in Step 5 of the diagnosis:
# on perf1
pgrep -o -x stress-ngThen with this PID (in the lab 174939):
# on perf1
sudo renice -n 19 -g 174939renicechanges the nice value of running processes.-n 19the new value.-gselects a process group instead of a single process. The stress-ng parent process is the leader of the group all workers belong to.
Expected:
174939 (process group ID) old priority 0, new priority 19
It changes nothing about the workers’ waiting time: they compete with each other, and all of them now have the same low weight – equal weights, equal shares. PSI keeps showing around 90 %. nice only helps other processes in the same cgroup that are to be preferred. Against an overcommitted CPU within a service only less work at the same time helps.
Save your progress? Sign up for free
Checkpoint
# on perf1
pgrep -c stress-ngExpected: 0.
# on perf1
systemctl list-units --failed --no-legendExpected: no output.
# on perf1
systemctl --user list-units --failed --no-legendExpected: no output.
# on perf1
sudo runqlat-bpfcc -m 2 1Expected: almost all events in the line 0 -> 1.
Test yourself
- What is the difference between utilization and saturation of the CPU, and with which two tools from today do you measure saturation?
- A process has many voluntary and hardly any involuntary context switches. What is it doing?
- A background job runs with nice 19 on an otherwise empty machine. How fast does it compute?
- A service with 16 threads creates load 16. Why does a program in your SSH session hardly notice?
- Why do 16 instead of 4 computing workers on 4 CPUs bring no throughput?
- How do you recognize steal, and what can you do about it inside the VM?
Answers:
- Utilization = all CPUs compute; saturation = threads additionally
wait in the run queue. Measure with
runqlat/runqlen, also withpidstat(%wait,nvcswch/s). - It waits a lot – for disk, network, a lock or a timer.
- At full speed – nice only has an effect when there is competition.
- systemd distributes the CPU first between cgroups
(
system.sliceanduser.slicewith weight 100 each); the service mainly slows down itself. - Four CPUs deliver the same amount no matter how many threads are waiting; more threads only make every single job longer (measured 2,980 versus 2,903 operations per second).
- By
stinvmstator%stealinmpstat/sar. Inside the VM nothing – only measure it and show it to the host operator.
Interview Note
“A service is slow, the load is at 16 on 4 cores. What do you do?” A
strong answer separates utilization and saturation (r, PSI,
runqlat, nvcswch/s), checks who is
waiting (pidstat %wait, cgroup) and asks the throughput
question: do more threads bring more at all? If you explain that with
pure compute load the optimal number of workers equals the number of
CPUs and that otherwise only latency rises, you prove understanding.
Knowledge of cgroup weights under systemd and of CPU steal in VMs rounds
it off – both are often not expected in interviews and leave an
impression.
Enterprise Note
In data centers and clouds steal is a contract issue: whoever rents
VMs should have %steal in monitoring and raise permanent
values above a few percent with the provider. In your own virtualization
cluster the ratio of virtual to real CPUs (vCPU overcommitment)
belongs in capacity planning; latency-sensitive systems such as
databases get reserved or dedicated cores. For applications: dimension
thread pools correctly and align their size with the number of
usable CPUs – in containers that is often not
nproc but the cgroup’s CPU limit (Day 15). And alerts on
load without context produce exactly the tickets from this diagnosis
task.
Summary
- Every CPU has a run queue; the scheduler (EEVDF
since kernel 6.6) distributes the CPU fairly by
weights.
runqlatmeasures the waiting time,runqlenthe length. - Voluntary context switches = waiting for something,
involuntary = CPU saturation (
pidstat -w,/proc/PID/sched). /proc/PID/schedstat: compute and waiting time of a process in nanoseconds.- nice from −20 to 19 changes the weight (1024 at 0, 15 at 19); it only has an effect when there is competition.
- Under systemd the cpu controller distributes the CPU first between cgroups, then within them: an overloaded service mainly slows down itself. High load does not say who suffers.
- Steal is time the hypervisor did not give; visible
as
st/%steal, not fixable inside the VM, caused by overcommitted hosts or hypervisor work (including I/O). - More computing threads than CPUs do not increase throughput, only latency – measured: 2,980 versus 2,903 operations per second, every job four times slower.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
runqlat-bpfcc -m 5 1 |
run queue waiting time as a histogram | -m milliseconds, interval, count |
runqlen-bpfcc 5 1 |
run queue length (samples) | interval, count |
pidstat -w 1 1 |
voluntary/involuntary context switches per process | -w switches |
pgrep -n NAME / pgrep -o -x NAME |
newest / oldest PID for a name | -x exact name |
cat /proc/PID/schedstat |
compute time, waiting time (ns), time slices | – |
grep -E "…" /proc/PID/sched |
detailed scheduler data | – |
nice -n 19 COMMAND |
start a command with low priority | -n nice value |
renice -n 19 -g PGID |
change the priority of running processes | -n value, -g process group,
-p process |
ps -o pid,ni,pri,psr,comm -C NAME |
nice value, priority and CPU per process | -C name |
cat /sys/fs/cgroup/…/cpu.weight |
CPU weight of a cgroup | – |
systemd-run --wait -q --pipe COMMAND |
start a command as a service and show its output | --wait, --pipe, -q |
stress-ng --cpu N --metrics-brief |
load with throughput measurement | --metrics-brief summary |
sar -u -f FILE -s … -e … |
steal and CPU from the recording | -f file, -s/-e window |