aboutsummaryrefslogtreecommitdiff
path: root/cpu.lua
blob: fba34077ac5229b5b1ac33d35fec57d4f1735578 (plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
----------------------------------------------------------
-- Licensed under the GNU General Public License version 2
--  * Copyright (C) 2009 Adrian C. <anrxc_sysphere_org>
--  * Derived from Wicked, copyright of Lucas de Vries
----------------------------------------------------------

-- {{{ Grab environment
local ipairs = ipairs
local io = { open = io.open }
local setmetatable = setmetatable
local math = { floor = math.floor }
local table = { insert = table.insert }
-- }}}


-- Cpu: provides CPU usage for all available CPUs/cores
module("vicious.cpu")


-- Initialise function tables
local cpu_usage  = {}
local cpu_total  = {}
local cpu_active = {}

-- {{{ CPU widget type
local function worker(format)
    -- Get /proc/stat
    local f = io.open("/proc/stat")
    local cpu_lines = {}

    for line in f:lines() do
        if line:find("^cpu") then
            if #cpu_lines < 1 then cpuid = 1
            else cpuid = #cpu_lines + 1 end

            cpu_lines[cpuid] = {}
            for match in line:gmatch("[%s]+([%d]+)") do
                  table.insert(cpu_lines[cpuid], match)
            end
        end
    end
    f:close()

    -- Ensure tables are initialized correctly
    while #cpu_total < #cpu_lines do
        table.insert(cpu_total, 0)
    end
    while #cpu_active < #cpu_lines do
        table.insert(cpu_active, 0)
    end
    while #cpu_usage < #cpu_lines do
        table.insert(cpu_usage, 0)
    end

    local total_new   = {}
    local active_new  = {}
    local diff_total  = {}
    local diff_active = {}

    for i, v in ipairs(cpu_lines) do
        -- Calculate totals
        total_new[i]  = 0
        for j = 1, #v do
            total_new[i] = total_new[i] + v[j]
        end
        active_new[i] = v[1] + v[2] + v[3]

        -- Calculate percentage
        diff_total[i]  = total_new[i]  - cpu_total[i]
        diff_active[i] = active_new[i] - cpu_active[i]
        cpu_usage[i]   = math.floor(diff_active[i] / diff_total[i] * 100)

        -- Store totals
        cpu_total[i]   = total_new[i]
        cpu_active[i]  = active_new[i]
    end

    return cpu_usage
end
-- }}}

setmetatable(_M, { __call = function(_, ...) return worker(...) end })