Debian Codegraph @

vicious/widgets/cpu_linux.lua

raw symbols SCIP
1 -- CPU usage widget type for GNU/Linux
2 -- Copyright (C) 2009 Lucas de Vries <[email protected]>
3 -- Copyright (C) 2011 Adrian C. <[email protected]>
4 -- Copyright (C) 2011 Jörg Thalheim <[email protected]>
5 -- Copyright (C) 2017 mutlusun <[email protected]>
6 --
7 -- This file is part of Vicious.
8 --
9 -- Vicious is free software: you can redistribute it and/or modify
10 -- it under the terms of the GNU General Public License as
11 -- published by the Free Software Foundation, either version 2 of the
12 -- License, or (at your option) any later version.
13 --
14 -- Vicious is distributed in the hope that it will be useful,
15 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
16 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 -- GNU General Public License for more details.
18 --
19 -- You should have received a copy of the GNU General Public License
20 -- along with Vicious. If not, see <https://www.gnu.org/licenses/>.
21
22 -- {{{ Grab environment
23 local ipairs = ipairs
24 local io = { open = io.open }
25 local math = { floor = math.floor }
26 local table = { insert = table.insert }
27 local string = {
28 sub = string.sub,
29 gmatch = string.gmatch
30 }
31
32 local helpers = require"vicious.helpers"
33 -- }}}
34
35 -- Initialize function tables
36 local cpu_usage = {}
37 local cpu_total = {}
38 local cpu_active = {}
39
40 -- {{{ CPU widget type
41 return helpers.setcall(function ()
42 local cpu_lines = {}
43
44 -- Get CPU stats
45 local f = io.open("/proc/stat")
46 for line in f:lines() do
47 if string.sub(line, 1, 3) ~= "cpu" then break end
48
49 cpu_lines[#cpu_lines+1] = {}
50
51 for i in string.gmatch(line, "[%s]+([^%s]+)") do
52 table.insert(cpu_lines[#cpu_lines], i)
53 end
54 end
55 f:close()
56
57 -- Ensure tables are initialized correctly
58 for i = #cpu_total + 1, #cpu_lines do
59 cpu_total[i] = 0
60 cpu_usage[i] = 0
61 cpu_active[i] = 0
62 end
63
64 for i, v in ipairs(cpu_lines) do
65 -- Calculate totals
66 local total_new = 0
67 for j = 1, #v do
68 total_new = total_new + v[j]
69 end
70 local active_new = total_new - (v[4] + v[5])
71
72 -- Calculate percentage
73 local diff_total = total_new - cpu_total[i]
74 local diff_active = active_new - cpu_active[i]
75
76 if diff_total == 0 then diff_total = 1E-6 end
77 cpu_usage[i] = math.floor((diff_active / diff_total) * 100)
78
79 -- Store totals
80 cpu_total[i] = total_new
81 cpu_active[i] = active_new
82 end
83
84 return cpu_usage
85 end)
86 -- }}}