cpu.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. --[[
  2. Licensed under GNU General Public License v2
  3. * (c) 2013, Luca CPZ
  4. * (c) 2010-2012, Peter Hofmann
  5. --]]
  6. local helpers = require("lain.helpers")
  7. local wibox = require("wibox")
  8. local math = math
  9. local string = string
  10. -- CPU usage
  11. -- lain.widget.cpu
  12. local function factory(args)
  13. args = args or {}
  14. local cpu = { core = {}, widget = args.widget or wibox.widget.textbox() }
  15. local timeout = args.timeout or 2
  16. local settings = args.settings or function() end
  17. function cpu.update()
  18. -- Read the amount of time the CPUs have spent performing
  19. -- different kinds of work. Read the first line of /proc/stat
  20. -- which is the sum of all CPUs.
  21. for index,time in pairs(helpers.lines_match("cpu","/proc/stat")) do
  22. local coreid = index - 1
  23. local core = cpu.core[coreid] or
  24. { last_active = 0 , last_total = 0, usage = 0 }
  25. local at = 1
  26. local idle = 0
  27. local total = 0
  28. for field in string.gmatch(time, "[%s]+([^%s]+)") do
  29. -- 4 = idle, 5 = ioWait. Essentially, the CPUs have done
  30. -- nothing during these times.
  31. if at == 4 or at == 5 then
  32. idle = idle + field
  33. end
  34. total = total + field
  35. at = at + 1
  36. end
  37. local active = total - idle
  38. if core.last_active ~= active or core.last_total ~= total then
  39. -- Read current data and calculate relative values.
  40. local dactive = active - core.last_active
  41. local dtotal = total - core.last_total
  42. local usage = math.ceil((dactive / dtotal) * 100)
  43. core.last_active = active
  44. core.last_total = total
  45. core.usage = usage
  46. -- Save current data for the next run.
  47. cpu.core[coreid] = core
  48. end
  49. end
  50. cpu_now = cpu.core
  51. cpu_now.usage = cpu_now[0].usage
  52. widget = cpu.widget
  53. settings()
  54. end
  55. helpers.newtimer("cpu", timeout, cpu.update)
  56. return cpu
  57. end
  58. return factory