Skip to content

Instantly share code, notes, and snippets.

@Igneous
Created December 20, 2010 06:42
Show Gist options
  • Save Igneous/748101 to your computer and use it in GitHub Desktop.
Save Igneous/748101 to your computer and use it in GitHub Desktop.
#!/usr/bin/lua
require "socket"
io.stdout:setvbuf "no"
prev_total = 0
prev_idle = 0
function round(number, decimal)
local multiplier = 10^(decimal or 0)
return math.floor(number * multiplier + 0.5) / multiplier
end
function sleep(sec)
socket.select(nil,nil,sec)
end
function getpct()
file = assert(io.open("/proc/stat", "r"))
--- Get the cpu line and insert each space-seperated value into a table
for line in file:lines() do
sfound = string.find(line, "cpu ", 1)
if sfound ~= nil then
cpu = {}
for word in line:gmatch("%S+") do
table.insert(cpu,word)
end
table.remove(cpu,1)
end
end
-- No need to keep this fd open any longer than we need to...
file:close()
-- Get the idle cpu time (the 5th number in the series of 10)
idle = cpu[4]
-- Calculate the total cpu time
total = 0
for row,cpuval in ipairs(cpu) do
total = total + cpuval
-- print("Loop run, total = ", total, " cpuval = ", cpuval)
end
-- Calculate the CPU usage since we last checked
diff_idle = idle - prev_idle
diff_total = total - prev_total
diff_usage = (1000 * (diff_total - diff_idle) / diff_total + 5) / 10
-- Remember the total and idle CPU times for the next check
prev_total = total
prev_idle = idle
return round(diff_usage, 0)
end
function gdbar(pct,fgcolor,bgcolor,x_dimension,y_dimension,maxpct)
gdbar_diff = maxpct / x_dimension
gdbar_div = pct / gdbar_diff
gdbar_rdiv = round(gdbar_div)
return("^fg(" .. fgcolor .. ")^r(" .. gdbar_rdiv .. "x" .. y_dimension .. ")^fg(" .. bgcolor .. ")^r(" .. x_dimension - gdbar_rdiv .. "x" .. y_dimension .. ")^fg()")
end
while true do
date = os.date("%A, %b %d. %I:%M%p")
cpu_pct = getpct()
print("^i(/home/igneous/.dzen/bitmaps/xbm8x8/cpu.xbm) " .. gdbar(cpu_pct,"white","darkgrey",80,10,100))
sleep(1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment