Debian Codegraph @

vicious/widgets/cpu_freebsd.lua

raw symbols SCIP
1 -- CPU usage widget type for FreeBSD
2 -- Copyright (C) 2017,2019 mutlusun <[email protected]>
3 -- Copyright (C) 2019 Nguyễn Gia Phong <[email protected]m>
4 --
5 -- This file is part of Vicious.
6 --
7 -- Vicious is free software: you can redistribute it and/or modify
8 -- it under the terms of the GNU General Public License as
9 -- published by the Free Software Foundation, either version 2 of the
10 -- License, or (at your option) any later version.
11 --
12 -- Vicious is distributed in the hope that it will be useful,
13 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
14 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 -- GNU General Public License for more details.
16 --
17 -- You should have received a copy of the GNU General Public License
18 -- along with Vicious. If not, see <https://www.gnu.org/licenses/>.
19
20 -- {{{ Grab environment
21 local math = { floor = math.floor }
22 local string = { gmatch = string.gmatch }
23
24 local helpers = require("vicious.helpers")
25 -- }}}
26
27 -- Cpu: provides CPU usage for all available CPUs/cores
28 -- vicious.widgets.cpu_freebsd
29 local cpu_freebsd = {}
30
31 -- Initialize function tables
32 local cpu_total = {}
33 local cpu_idle = {}
34
35 -- {{{ CPU widget type
36 function cpu_freebsd.async(format, warg, callback)
37 local matches = {}
38 local tmp_total = {}
39 local tmp_idle = {}
40 local tmp_usage = {}
41
42 helpers.sysctl_async({ "kern.cp_times" }, function(ret)
43 -- Read input data
44 for v in string.gmatch(ret["kern.cp_times"], "([%d]+)") do
45 table.insert(matches, v)
46 end
47
48 -- Set first value of function tables
49 if #cpu_total == 0 then -- check for empty table
50 for i = 1, #matches / 5 + 1 do
51 cpu_total[i] = 0
52 cpu_idle[i] = 0
53 end
54 end
55 for i = 1, #matches / 5 + 1 do
56 tmp_total[i] = 0
57 tmp_idle[i] = 0
58 tmp_usage[i] = 0
59 end
60
61 -- CPU usage
62 for i, v in ipairs(matches) do
63 local index = math.floor((i-1) / 5) + 2 -- current cpu
64
65 tmp_total[1] = tmp_total[1] + v
66 tmp_total[index] = tmp_total[index] + v
67
68 if (i-1) % 5 == 4 then
69 tmp_idle[1] = tmp_idle[1] + v
70 tmp_idle[index] = tmp_idle[index] + v
71 end
72 end
73
74 for i = 1, #tmp_usage do
75 tmp_usage[i] = tmp_total[i] - cpu_total[i]
76 tmp_usage[i] = math.floor(
77 (tmp_usage[i] - (tmp_idle[i] - cpu_idle[i]))
78 / tmp_usage[i] * 100)
79 end
80
81 cpu_total = tmp_total
82 cpu_idle = tmp_idle
83
84 return callback(tmp_usage)
85 end)
86 end
87 -- }}}
88
89 return helpers.setasyncall(cpu_freebsd)