Debian Codegraph @

obvious/cpu/init.lua

raw symbols SCIP
1 -----------------------------------
2 -- Author: Uli Schlachter --
3 -- Copyright 2009 Uli Schlachter --
4 -----------------------------------
5
6 local io = io
7 local tonumber = tonumber
8 local pairs = pairs
9 local setmetatable = setmetatable
10 local lib = {
11 widget = require("obvious.lib.widget")
12 }
13
14 local function cpu_info()
15 local f = io.open("/proc/stat")
16 local line = f:read()
17 local ret = { }
18 local matches = line:gmatch("%d+")
19
20 f:close()
21
22 -- each time matches() is called it returns the next number from line
23 ret.user = tonumber(matches())
24 ret.nice = tonumber(matches())
25 ret.system = tonumber(matches())
26 ret.idle = tonumber(matches())
27 ret.iowait = tonumber(matches())
28 ret.irq = tonumber(matches())
29 ret.softirq = tonumber(matches())
30
31 -- The returned array contains numbers which describe the time in number of
32 -- jiffies since this box was started
33 return ret
34 end
35
36 local function cpu_usage(object)
37 local last = object.cpu_last
38 local cur = cpu_info()
39 object.cpu_last = cur
40
41 -- Fake for starting
42 if last == nil then
43 last = cur
44 end
45
46 local ret = { }
47 for k, v in pairs(cur) do
48 ret[k] = cur[k] - last[k]
49 end
50
51 -- Calculate the cpu usage in percent
52 -- Ignore iowait (dunno...)
53 local t = ret.user + ret.nice + ret.system + ret.irq + ret.softirq
54 if (t + ret.idle) == 0 then
55 ret.perc = 0
56 else
57 ret.perc = 100 * t / (t + ret.idle)
58 end
59
60 -- This array now got the following keys (time is in jiffies!):
61 -- * user user cpu time
62 -- * nice cpu time for nice'd processes
63 -- * system cpu time spent in syscalls
64 -- * idle cpu time spent idlying
65 -- * iowait cpu time spent waiting for I/O
66 -- * irq cpu time spent in irq handlers
67 -- * softirq cpu time spent in soft irq handlers
68 -- * perc percentage of time spent doing stuff
69 return ret
70 end
71
72 local function get_data_source()
73 local ret = {}
74
75 ret.max = 100
76 ret.get = function(obj)
77 return cpu_usage(obj).perc
78 end
79
80 return lib.widget.from_data_source(ret)
81 end
82
83 return setmetatable({}, { __call = function (_, ...) return get_data_source(...) end })
84
85 -- vim:ft=lua:ts=2:sw=2:sts=2:tw=80:et