Here’s a Lua function that returns the percentage of CPU used on Linux. The load includes time in user space and system space. In case you’re curious, I used `top` to get the load for a couple reasons:
- It’s installed by default on most distros (as opposed to the
sysstattools). - It gives the idle time in percentage normalized to 100% (as opposed to
/proc/statwhich requires knowledge of the jiffy’s interval, which can vary).
function cpu_load(interval)
interval = interval or 1
local f = io.popen('top -bp$$ -d ' .. interval .. ' -n 2')
local s = f:read('*all')
-- Find the idle times in the stdout output
local tokens = s:gmatch(',%s*([%d%.]+)%%%s*id')
-- We're interested in the 2nd 'top' idle time
local ii = 1
for idle in tokens do
if ii == 2 then
return 100.0 - tonumber(idle)
end
ii = ii + 1
end
end
You can call it from the Lua shell as:
> load = cpu_load()
> print(load)
43.7

