Every time I open top I take it for granted. The percentages look live, as if the kernel were computing them. It is not. /proc/stat never reports a percentage. It reports counters that only go up, and every tool you use top, htop, btop is doing the same subtraction you can do yourself.
I implemented that subtraction for the CPU collector in serverctl, and the interesting part was not the formula. It was the two moments where the naive version gives you a wrong number and nothing warns you.
What is actually inside the file
The first lines of /proc/stat look like this:
cpu 1000 0 500 8000 200 0 100 0 0 0 cpu0 250 0 125 2000 50 0 25 0 0 0 cpu1 250 0 125 2000 50 0 25 0 0 0 The cpu line is the aggregate, and cpu0, cpu1, and so on are the individual cores. Each column is a cumulative count of jiffies since boot, in this order:
-
user— normal processes in user space -
nice— niced processes in user space -
system— kernel time -
idle— idle -
iowait— waiting on I/O -
irq— hardware interrupts -
softirq— software interrupts -
steal— time the hypervisor took away from this machine -
guest,guest_nice— time running a guest VM's CPU
A jiffy is usually 10 milliseconds (USER_HZ = 100). So those numbers are not milliseconds and they are not percentages. They are ticks.
The formula
Take two samples, subtract, and the delta tells you how your cores spent the last interval:
usage = 1 - (idle_delta / total_delta) That is the whole idea. In Go, with the eight counters that matter:
func UsagePercent(prev, curr CPUSample) float64 { totalDelta := curr.Total() - prev.Total() if totalDelta == 0 { return 0 } idleDelta := curr.IdleTime() - prev.IdleTime() return (1 - float64(idleDelta)/float64(totalDelta)) * 100 } Two details in those six lines are not accidental. totalDelta == 0 returns 0 instead of NaN, because two reads that land on the same tick are possible and a NaN in a dashboard is a bug that travels. And IdleTime() is idle + iowait, which is a decision I will come back to.
Why the first reading always lies
Here is the trap. You open the file once, compute 1 - idle/total, and get a number. That number is the average CPU usage since the machine booted, not now.
It is also, in practice, not even that. It is the average since boot computed from a single sample, which means it is a statistic about the last three days of uptime shown in a widget labelled "now". A server that has been idle for a week and just started compiling will show 2%.
So the collector keeps exactly one piece of state:
type CPUTracker struct { prev CPUSample prevPer []CPUSample started bool } On the first Refresh, there is nothing to subtract from. The honest thing to do is say so:
if !t.started { t.prev, t.prevPer, t.started = aggregate, perCPU, true return 0, make([]float64, len(perCPU)), false } That third return value is measured. The first call reports 0 and false, and the dashboard renders "measuring…" instead of a fake 0%. The difference between "I don't know yet" and "zero" is the difference between a correct dashboard and a liar.
In internal/core/models.go that becomes a field with a comment I wrote for future me:
Measured bool // false on the first round, before a baseline sample The second trap: sampling too fast
If one jiffy is 10 ms, reading the file every 100 ms gives you roughly 10 ticks per core to work with. Ten. Your error is on the order of one tick out of ten around 10% and it will jump around because the rounding is not smooth.
At the 2-second interval serverctl uses by default, you get around 200 ticks per core and the quantization almost disappears.
So "smoother" sampling makes the number worse, not better. If you want a responsive graph, smooth the values you already have; do not read the kernel more often.
The two decisions nobody documents
Guest time is already inside user time. Since Linux 2.6.24, the time a VM spends on a virtual CPU is counted in user and nice as well as in guest. Add both columns to your total and you count it twice, which inflates the denominator and reports less usage than there is. My parser takes the first eight counters and deliberately stops before guest:
sample, err := parseCPULine(fields[1:9]) It is not laziness. It is the correct total.
Iowait counts as idle in my implementation, so a machine blocked on a slow disk shows low CPU usage. That is defensible the CPU is genuinely not executing but it is not the same as "the machine is fine". If your service is slow while CPU sits at 5%, the interesting number is not in this file at all: it is in steal, or in your disk latency.
How to test it without touching the kernel
The collector takes a root path:
type System struct{ root string } func New(root string) System { return System{root: root} } Production passes /. Tests pass a directory with a fixture that looks exactly like the real file:
cpu 1000 0 500 8000 200 0 100 0 0 0 cpu0 250 0 125 2000 50 0 25 0 0 0 cpu1 250 0 125 2000 50 0 25 0 0 0 With that, I can test the aggregate, the per-core parsing, a malformed line, an empty file and a missing aggregate row, without a VM and without depending on whatever my PC is doing during the test run.
If you take one idea from this post, take that one: a collector that cannot be pointed at a fixture is a collector you will never trust.
The short version
/proc/stat gives you counters. You need two samples. The first one lies because it has no baseline, so report "not measured yet" instead of zero. Do not sample faster than your tick resolution allows. Do not add guest to user. And decide, explicitly, what iowait means to you.
Everything top shows you is that, plus formatting.

