1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
local wibox = require("wibox")
local widgets = require("util.widgets")
local gears = require("gears")
-- this is directly adapted from slstatus's cpu.c module
local cpu_time = { 0,0,0,0,0,0,0 } -- user, nice, system, idle, iowait, irq, softirq
function linux_cpu_usage(widget)
-- read stat
local statf = io.open("/proc/stat")
local stat_iter = statf:read():gmatch("%d+")
statf:close()
-- calc
local sum = 0
local a = cpu_time -- set cpu_time as a for smaller code
local b = gears.table.clone(a) -- copy a to b
for i = 1, 7 do
a[i] = stat_iter()
sum = sum + b[i] - a[i]
end
if sum == 0 then
return
end
local usage = ((b[1] + b[2] + b[3] + b[6] + b[7]) -
(a[1] + a[2] + a[3] + a[6] + a[7])) * 100 / sum
widget:set_text(math.floor(usage))
end
-- return correct widget for os
if osname == "Linux" then
return widgets.watchfn(linux_cpu_usage, 5)
end
return wibox.widget.textbox("unsupported os")
|