From ca37eff5b6817e95ce5b6cfd768fd27c9af96914 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Wed, 16 Sep 2026 19:24:48 +0200 Subject: feat: add stateful CPU percentage counter Load is a delta, so one reading cannot yield a percentage. The first call returns nil rather than a fabricated number: 100% on startup reads as a real spike. A non-advancing counter also returns nil instead of dividing by zero, and the result is clamped because a suspend/resume can produce a nonsense delta. Co-Authored-By: Claude Opus 5 --- lib/data.lua | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'lib') diff --git a/lib/data.lua b/lib/data.lua index 96fc172..28dce1e 100644 --- a/lib/data.lua +++ b/lib/data.lua @@ -72,4 +72,31 @@ function M.hwmon_dir(name) return hit:match('^(.*)/name$') end +-- A stateful CPU-load counter. +-- +-- Load is work done between two samples, so a single reading cannot produce a +-- percentage. Each counter keeps its own previous sample, which also means a +-- per-core counter is just another instance. +function M.new_cpu_counter() + return { + prev_total = nil, + prev_idle = nil, + -- Returns busy percent since the previous sample, or nil when there is no + -- usable delta (first call, or the counters did not advance). + sample = function(self, total, idle) + if not (total and idle) then return nil end + local pt, pi = self.prev_total, self.prev_idle + self.prev_total, self.prev_idle = total, idle + if not pt then return nil end + local dt = total - pt + if dt <= 0 then return nil end + local busy = (dt - (idle - pi)) / dt * 100 + -- Clamp: a counter reset or a suspend/resume can produce a nonsense + -- delta, and a bar drawn at -12% or 340% is worse than a clamped one. + if busy < 0 then busy = 0 elseif busy > 100 then busy = 100 end + return busy + end, + } +end + return M -- cgit v1.2.3