Monitoring CPU, Memory, and System Load
When a server becomes slow, the first questions are always the same: Is the CPU busy? Is the machine short of memory? Are processes waiting in line to run? Lesson 143 looked at individual processes with ps, pgrep and top. This lesson looks at the whole system: how Linux measures CPU use, what the load average really counts, which memory figure tells you whether the machine is running out, and how a Bash script can read these numbers directly from the kernel and raise a warning when they cross a limit.
Almost every monitoring tool on Linux, from top and free to large monitoring agents, reads the same small set of files in the /proc file system. /proc is not stored on disk; the kernel generates its files on the fly when they are read. A Bash script can read them as easily as any text file, without installing anything.
| What you want to know | Source |
|---|---|
| Number of CPUs | nproc |
| CPU time spent working and idle | /proc/stat |
| Load averages | /proc/loadavg (also shown by uptime) |
| Memory and swap | /proc/meminfo (also shown by free) |
| How long tasks wait for CPU, memory or disk | /proc/pressure/cpu, memory, io |
CPU Usage
How Linux counts CPU time
A CPU is either running something or idle; there is no "half busy" at any single instant. A CPU percentage is therefore always an average over a period: of the last 2 seconds, how much time was spent working?
The kernel keeps running totals of CPU time since boot in the first line of /proc/stat, measured in clock ticks (usually 100 per second; getconf CLK_TCK shows the value):
head -1 /proc/stat
cpu 12534 0 22685 88716 105 0 119 481 0 0
The first line, labelled cpu, adds up all CPUs. Lines cpu0, cpu1 and so on follow for each CPU. The numbers are, in order:
| Field | Meaning |
|---|---|
user | running ordinary program code |
nice | running program code with a lowered priority (nice) |
system | running kernel code on behalf of programs |
idle | doing nothing |
iowait | idle while some task waits for disk I/O |
irq, softirq | handling hardware and software interrupts |
steal | time a virtual machine wanted the CPU but the host gave it to another guest |
guest, guest_nice | running virtual machines (already included in user and nice) |
Because the numbers only grow, one reading by itself says nothing about the present. You read the file twice, a few seconds apart, and compare the differences: busy time ÷ total time over that interval. iowait counts as idle time (the CPU could have run something else), and guest and guest_nice are left out because they are already part of user and nice.
Measuring CPU use from Bash
# cpu_sample: print "busy total" jiffies from the first line of /proc/stat
cpu_sample() {
local label user nice system idle iowait irq softirq steal
read -r label user nice system idle iowait irq softirq steal _ < /proc/stat
echo "$(( user + nice + system + irq + softirq + steal )) \
$(( user + nice + system + idle + iowait + irq + softirq + steal ))"
}
read -r busy1 total1 < <(cpu_sample)
sleep 1
read -r busy2 total2 < <(cpu_sample)
echo "busy jiffies: $(( busy2 - busy1 )), total jiffies: $(( total2 - total1 ))"
echo "CPU busy: $(( 100 * (busy2 - busy1) / (total2 - total1) ))%"
read reads only the first line of the file, splits it into the named variables, and puts any remaining fields into _, a throwaway variable. ("Jiffies" is the kernel's name for these ticks.) On an idle machine with 2 CPUs:
busy jiffies: 0, total jiffies: 199
CPU busy: 0%
In one second, two CPUs provide about 200 ticks. With one busy process (yes > /dev/null &) running:
busy jiffies: 102, total jiffies: 202
CPU busy: 50%
One process can keep only one CPU busy, so on a 2-CPU machine it shows as 50%. This matters when you read tools: top shows a process using one full CPU as 100%, while system-wide figures, like this one, are percentages of all CPUs together.
Reading the result
High CPU use is not a problem by itself; a build server or video encoder is supposed to use all its CPUs. It becomes a problem when it lasts and work starts to queue, which is what the load average shows. Two other fields deserve attention: a high iowait means the CPUs are waiting for the disk, not working, and on virtual machines a high steal means the host is overcommitted, which no change inside the virtual machine can fix.
The Load Average
uptime prints how long the system has been running and three load averages:
uptime
cat /proc/loadavg
nproc
15:03:01 up 10 min, 0 user, load average: 2.23, 1.19, 0.50
2.23 1.19 0.50 1/109 1343
2
The three numbers are averages over roughly the last 1, 5 and 15 minutes. /proc/loadavg adds two more fields: 1/109 means 1 task was running at that instant out of 109 that exist, and 1343 is the most recently created process ID.
What the load counts
The load is the average number of tasks that are running or ready to run (waiting for a CPU). On Linux, it also counts tasks in uninterruptible sleep, usually waiting for disk or network storage. So:
- On a machine with 2 CPUs, a load of 2.0 means that, on average, both CPUs were fully used and nothing had to wait.
- A load of 4.0 on the same machine means that, on average, two tasks were waiting for every task running.
- A load of 1.0 on a 16-CPU machine is almost nothing.
The load must therefore always be compared with the number of CPUs (nproc). Dividing the load by the CPU count gives the load per CPU; values that stay above 1.0 mean work is queuing. Because disk waits are included, a high load with low CPU use usually points at slow storage rather than busy CPUs.
The averages are exponentially damped: recent seconds count more, but old activity fades slowly. The output above was taken right after a test that had kept the CPUs busy: the system was already idle, yet the 1-minute load was still 2.23. For alerts, the 5-minute value is a good compromise: it ignores short spikes but reacts within minutes.
Memory
free and /proc/meminfo
free -h
total used free shared buff/cache available
Mem: 7.8Gi 588Mi 7.1Gi 12Mi 357Mi 7.3Gi
Swap: 0B 0B 0B
The most important column is available, not free. Linux uses otherwise unused memory as a page cache, which keeps recently read file data in memory so it does not have to be read from disk again. This shows as buff/cache. When a program needs memory, the kernel simply drops cached data. So memory used by the cache is, for the most part, still available. A machine that shows little free memory but plenty available memory is healthy; Linux is just making good use of RAM.
free takes its figures from /proc/meminfo, which a script can read directly. Values are in KiB:
grep -E '^(MemTotal|MemFree|MemAvailable|Buffers|Cached|SwapTotal|SwapFree):' /proc/meminfo
MemTotal: 8216208 kB
MemFree: 7485776 kB
MemAvailable: 7613476 kB
Buffers: 13488 kB
Cached: 343320 kB
SwapTotal: 0 kB
SwapFree: 0 kB
MemAvailable is the kernel's own estimate of how much memory new programs can use without the system starting to swap. It accounts for which cached pages can actually be dropped. Scripts should use it rather than trying to add up MemFree, Buffers and Cached; that sum overestimates, because not every cached page can be freed.
Swap and the OOM killer
Swap is disk space used as an overflow for memory. When RAM runs short, the kernel moves pages that have not been used recently to swap. A little swap use is normal. Heavy and growing swap use, together with low MemAvailable, means the machine needs more memory than it has, and it slows down sharply because the disk is thousands of times slower than RAM. Many cloud servers and containers have no swap at all (SwapTotal: 0).
When neither RAM nor swap can satisfy a request, the Linux out-of-memory (OOM) killer ends a process to free memory, usually the one using the most. When this lesson's examples were tested, three Python processes allocating 2.45 GB each on an 8 GB machine triggered it, and Bash reported one of them as killed:
t5.sh: line 6: 1390 Killed python3 /srv/t167/hog.py 2450000000 20
The kernel log (journalctl -k or dmesg, with root rights) records each OOM kill. A memory check aims to warn before this point.
Processes using the most memory
ps can sort by resident set size (RSS), the amount of RAM a process is actually using, in KiB:
ps -eo pid,user,rss,pmem,comm --sort=-rss | head -n 4
The pmem column is RSS as a percentage of total memory. Shared libraries are counted in the RSS of every process that uses them, so the RSS values of many processes added together can exceed the memory in use.
Other Views: vmstat and Pressure Stall Information
vmstat prints a compact line of system statistics every interval. vmstat 1 3 prints three lines, one second apart:
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
r b swpd free buff cache si so bi bo in cs us sy id wa st gu
0 0 0 7485776 13488 353100 0 0 407 420 252 1 10 18 71 0 0 0
0 0 0 7485776 13488 353140 0 0 0 0 96 114 1 0 100 0 0 0
0 0 0 7485776 13488 353140 0 0 0 0 93 118 0 0 100 0 0 0
The first line is an average since boot; only the following lines describe the present. Useful columns are r (tasks running or waiting for a CPU), b (tasks blocked on I/O), si/so (memory swapped in and out per second; steady non-zero values mean the machine is short of memory) and us, sy, id, wa, st (user, system, idle, I/O wait and steal, in percent).
Newer kernels (4.20 and later, when enabled) also provide Pressure Stall Information in /proc/pressure/. Instead of asking how busy a resource is, it measures how much time tasks were delayed because the resource was short:
cat /proc/pressure/cpu
some avg10=19.43 avg60=33.85 avg300=18.56 total=83661941
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
some avg60=33.85 means that, over the last 60 seconds, at least one task was waiting for a CPU 33.85% of the time; this was measured while three busy processes competed for two CPUs. full counts time when all non-idle tasks were stalled at once. The same format exists for memory and io. Pressure values answer "is anyone actually suffering?" more directly than utilization, and a script can read them the same way as the other files.
A Complete Example: A System Load Check
sysload-check.sh measures CPU use over a short interval, compares the 5-minute load per CPU, available memory and swap use with limits, prints one line per check, and can list the processes responsible when something is wrong.
#!/usr/bin/env bash
#
# sysload-check.sh - check CPU use, load average, memory and swap
#
# Usage: sysload-check.sh [-i SECONDS] [-c CPU%] [-l LOAD] [-m MEM%] [-s SWAP%] [-p]
# -i SECONDS how long to measure CPU use (default: 2)
# -c CPU% warn when CPU use is at least this percent (default: 90)
# -l LOAD warn when the 5-minute load per CPU is at least this,
# e.g. 1.5 (default: 1.0)
# -m MEM% warn when available memory is below this percent (default: 10)
# -s SWAP% warn when swap use is at least this percent (default: 50)
# -p on a CPU/load or memory/swap warning, also list the
# processes using the most CPU or memory
#
# Exit status: 0 OK, 1 WARNING, 3 UNKNOWN (bad options or unreadable /proc)
set -uo pipefail
interval=2 cpu_warn=90 load_warn=1.0 mem_warn=10 swap_warn=50 show_procs=0
status=0
cpu_problem=0 mem_problem=0
die() { echo "${0##*/}: $*" >&2; exit 3; }
usage() { echo "usage: ${0##*/} [-i SECONDS] [-c CPU%] [-l LOAD] [-m MEM%] [-s SWAP%] [-p]" >&2; exit 3; }
# report NAME OK|WARNING TEXT: print one aligned result line
report() {
printf '%-7s %-8s %s\n' "$1" "$2" "$3"
[[ $2 == WARNING ]] && status=1
return 0
}
# hundredths 1.5 -> 150: turn a number with up to two decimals into an integer
hundredths() {
local whole=${1%%.*} frac=
[[ $1 == *.* ]] && frac=${1#*.}
frac=${frac}00
echo $(( 10#$whole * 100 + 10#${frac:0:2} ))
}
# cpu_sample: print "busy total" CPU time (in clock ticks) since boot
cpu_sample() {
local label user nice system idle iowait irq softirq steal
read -r label user nice system idle iowait irq softirq steal _ < /proc/stat ||
die "cannot read /proc/stat"
echo "$(( user + nice + system + irq + softirq + steal ))" \
"$(( user + nice + system + idle + iowait + irq + softirq + steal ))"
}
# meminfo KEY: print one value (in KiB) from /proc/meminfo
meminfo() {
awk -v key="$1:" '$1 == key { print $2; found = 1 } END { exit !found }' /proc/meminfo ||
die "no $1 in /proc/meminfo"
}
human() { numfmt --from-unit=1024 --to=iec --round=nearest "$1"; }
while getopts ':i:c:l:m:s:p' opt; do
case $opt in
i) interval=$OPTARG ;;
c) cpu_warn=$OPTARG ;;
l) load_warn=$OPTARG ;;
m) mem_warn=$OPTARG ;;
s) swap_warn=$OPTARG ;;
p) show_procs=1 ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 0 )) || usage
for n in "$interval" "$cpu_warn" "$mem_warn" "$swap_warn"; do
[[ $n =~ ^[0-9]{1,3}$ ]] || die "not a whole number from 0 to 999: '$n'"
done
[[ $load_warn =~ ^[0-9]{1,3}(\.[0-9]{1,2})?$ ]] || die "LOAD must look like 1 or 1.5: '$load_warn'"
interval=$((10#$interval)) cpu_warn=$((10#$cpu_warn))
mem_warn=$((10#$mem_warn)) swap_warn=$((10#$swap_warn))
(( interval >= 1 )) || die "SECONDS must be at least 1"
cpus=$(nproc) || die "nproc failed"
# --- CPU: two samples of /proc/stat, INTERVAL seconds apart
sample1=$(cpu_sample) || exit 3
sleep "$interval"
sample2=$(cpu_sample) || exit 3
read -r busy1 total1 <<< "$sample1"
read -r busy2 total2 <<< "$sample2"
(( total2 > total1 )) || die "CPU counters did not advance"
cpu_pct=$(( 100 * (busy2 - busy1) / (total2 - total1) ))
level=OK; (( cpu_pct >= cpu_warn )) && level=WARNING cpu_problem=1
report CPU "$level" "${cpu_pct}% busy over ${interval}s on $cpus CPUs (warn at ${cpu_warn}%)"
# --- Load: the 5-minute average, compared per CPU
read -r load1 load5 load15 _ < /proc/loadavg || die "cannot read /proc/loadavg"
per_cpu=$(( $(hundredths "$load5") / cpus )) # in hundredths
level=OK; (( per_cpu >= $(hundredths "$load_warn") )) && level=WARNING cpu_problem=1
report LOAD "$level" "$load1 $load5 $load15 (5-min $(printf '%d.%02d' $((per_cpu / 100)) $((per_cpu % 100))) per CPU, warn at $load_warn)"
# --- Memory: MemAvailable is what new programs can get without swapping
mem_total=$(meminfo MemTotal) || exit 3
mem_avail=$(meminfo MemAvailable) || exit 3
mem_pct=$(( 100 * mem_avail / mem_total ))
level=OK; (( mem_pct < mem_warn )) && level=WARNING mem_problem=1
report MEMORY "$level" "$(human "$mem_avail") of $(human "$mem_total") available (${mem_pct}%, warn below ${mem_warn}%)"
# --- Swap: may not exist at all
swap_total=$(meminfo SwapTotal) || exit 3
if (( swap_total == 0 )); then
report SWAP OK "none configured"
else
swap_free=$(meminfo SwapFree) || exit 3
swap_used=$(( swap_total - swap_free ))
swap_pct=$(( 100 * swap_used / swap_total ))
level=OK; (( swap_pct >= swap_warn )) && level=WARNING mem_problem=1
report SWAP "$level" "$(human "$swap_used") of $(human "$swap_total") used (${swap_pct}%, warn at ${swap_warn}%)"
fi
if (( show_procs && cpu_problem )); then
echo
echo "Top processes by CPU (measured by top over 1 second):"
top -b -n 2 -d 1 -o %CPU -w 512 |
awk '/^ *PID /{ n++ } n == 2 { printf "%7s %-8s %5s %5s %s\n", $1, $2, $9, $10, $12 }' |
head -n 4
fi
if (( show_procs && mem_problem )); then
echo
echo "Top processes by memory (resident set size in KiB):"
ps -eo pid,user,rss,pmem,comm --sort=-rss | head -n 4
fi
exit "$status"
How It Works
- Options and limits. Whole-number options are checked with a regular expression and read as decimal with
10#. The load limit may have up to two decimals (1.5), because load averages are decimal numbers. - Decimals without floating point. Bash arithmetic works only with integers.
hundredthsturns1.5into150and0.63into63by splitting at the dot and padding the fraction to two digits (frac=${frac}00, then the first two characters). The 5-minute load and the limit are both compared in hundredths, andprintf '%d.%02d'turns the result back into a decimal for display./proc/loadavgalways prints two decimal places, so no precision is lost. - CPU.
cpu_sampleis called twice,INTERVALseconds apart, exactly as in the earlier example. It runs inside$( ), a subshell, so thedieinside it can only end that subshell;|| exit 3makes the main script stop too (lesson 125). A check that the totals actually increased prevents a division by zero. - Load. The 5-minute load is divided by the number of CPUs, so the same limit works on a 2-CPU laptop and a 64-CPU server.
- Memory and swap.
meminfolooks up one key withawkand returns a non-zero status when the key is missing (exit !found), for exampleMemAvailableon very old kernels. The memory check usesMemAvailable. Swap is checked only if it exists, which also avoids dividing by zero. - Result and exit status.
reportprints aligned lines and setsstatusto 1 on any warning. The script ends with 0 (OK) or 1 (WARNING), and with 3 (UNKNOWN) when it cannot do its job, following the same monitoring convention asdisk-check.shin lesson 166. - Finding the cause. With
-p, a CPU or load warning lists the busiest processes and a memory or swap warning lists the largest ones. For CPU, the script does not useps %CPU, which is an average over each process's whole lifetime (lesson 143). It runstopin batch mode for two updates one second apart (-b -n 2 -d 1), sorted by CPU (-o %CPU), with a wide line (-w 512) so command names are not cut. The first update has no earlier measurement to compare with, soawkcounts thePIDheader lines and prints only the rows after the second one. For memory,ps --sort=-rssis accurate, because RSS is a current value.
Running the Complete Example
On an idle machine with 2 CPUs and no swap:
$ sysload-check.sh
CPU OK 3% busy over 2s on 2 CPUs (warn at 90%)
LOAD OK 0.67 0.63 0.27 (5-min 0.31 per CPU, warn at 1.0)
MEMORY OK 7.2G of 7.8G available (91%, warn below 10%)
SWAP OK none configured
status 0
Three busy processes (yes > /dev/null) were started and left running for 75 seconds. A deliberately low load limit of 0.3 shows how both CPU checks react:
$ sysload-check.sh -l 0.3 -p
CPU WARNING 100% busy over 2s on 2 CPUs (warn at 90%)
LOAD WARNING 2.42 1.21 0.50 (5-min 0.60 per CPU, warn at 0.3)
MEMORY OK 7.3G of 7.8G available (92%, warn below 10%)
SWAP OK none configured
Top processes by CPU (measured by top over 1 second):
PID USER %CPU %MEM COMMAND
1149 root 73.0 0.0 yes
1148 root 70.0 0.0 yes
1150 root 57.0 0.0 yes
status 1
Three processes share two CPUs, so together they use 200% in top's per-CPU terms and 100% of the machine. After 75 seconds the 1-minute load (2.42) is approaching 3, the number of tasks competing for the CPUs, while the 5-minute load (1.21) is still rising; this lag is why the script uses the 5-minute value for alerts.
Next, three Python processes each held 2 GB of memory. With the memory limit raised to 25%:
$ sysload-check.sh -i 1 -m 25 -p
CPU OK 0% busy over 1s on 2 CPUs (warn at 90%)
LOAD OK 0.94 0.68 0.27 (5-min 0.34 per CPU, warn at 1.0)
MEMORY WARNING 1.7G of 7.8G available (21%, warn below 25%)
SWAP OK none configured
Top processes by memory (resident set size in KiB):
PID USER RSS %MEM COMMAND
1081 root 1964148 23.9 python3
1080 root 1964112 23.9 python3
1082 root 1964104 23.9 python3
status 1
Only the memory list appears, because only a memory check failed. To test the swap branch, a 64 MB swap file was enabled and the memory processes were made larger; the start of that run (the process list that followed is not shown) was:
$ sysload-check.sh -i 1 -p
CPU OK 0% busy over 1s on 2 CPUs (warn at 90%)
LOAD OK 1.52 1.10 0.49 (5-min 0.55 per CPU, warn at 1.0)
MEMORY OK 2.7G of 7.8G available (34%, warn below 10%)
SWAP WARNING 60M of 64M used (93%, warn at 50%)
In that run the OOM killer had already ended one of the three processes, which is why available memory had recovered to 34% while swap was nearly full. Once the remaining processes finished, a new check still reported 12M of 64M used: the kernel does not bring pages back from swap until something needs them, so swap use can stay above zero long after memory pressure has passed.
Invalid options are reported with status 3:
$ sysload-check.sh extra
usage: sysload-check.sh [-i SECONDS] [-c CPU%] [-l LOAD] [-m MEM%] [-s SWAP%] [-p]
status 3
$ sysload-check.sh -c 101x
sysload-check.sh: not a whole number from 0 to 999: '101x'
status 3
$ sysload-check.sh -i 0
sysload-check.sh: SECONDS must be at least 1
status 3
$ sysload-check.sh -l 1.555
sysload-check.sh: LOAD must look like 1 or 1.5: '1.555'
status 3
A single run gives a snapshot. To see trends, schedule the script (lesson 170) every few minutes, append its output with a timestamp to a log (lesson 115), and alert only when the status is non-zero several times in a row, so that a short, harmless spike does not wake anyone up.