CPU Usage

From awesome
Jump to: navigation, search

This article will show the user how to add a simple CPU Usage display to their Awesome status bar. This widget is written in pure Lua, without any external programs or scripts, and gets the CPU information by polling /proc/stat. This code was tested on awesome 3.3pre20090421-1 with the kernel 2.6.29-ARCH. Adjustments may be necessary for other systems.

The Code[edit]

The function to retrieve the CPU information from /proc/stat is as follows:

   jiffies = {}
   function activecpu()
       local s = ""
       for line in io.lines("/proc/stat") do
           local cpu, newjiffies = string.match(line, "(cpu%d*)\ +(%d+)")
           if cpu and newjiffies then
               if not jiffies[cpu] then
                   jiffies[cpu] = newjiffies
               end
               --The string.format prevents your task list from jumping around 
               --when CPU usage goes above/below 10%
               s = s .. " " .. cpu .. ": " .. string.format("%02d", newjiffies-jiffies[cpu]) .. "% "
               jiffies[cpu] = newjiffies
           end
       end
       return s
   end

This code first defines a table to store old values for each processor. Inside the function, it reads /proc/stat line by line looking for processors. When it finds one, it reads the name and the processor and the current value for user processes, measured in jiffies. A "jiffy", in this context, is a unit of time equal to 1/100th of a second. The kernel counts how many jiffies were spent in each of the possible "modes", including, but not limited to, user processes, system processes, and idle time. To get the processor utilization in percent, we can simply pole user jiffies at a frequency of 1Hz and take the difference of the two measurements. The resulting values are formatted into a string and returned as the result of the function.

Next we create a text box to display the information in:

   cpuinfo = widget({ type = "textbox", align = "right" })

And register the hook to update the display.

   awful.hooks.timer.register(1, function() cpuinfo.text = activecpu() end)

Note that this updates every one second. This is important. If you want to make updates more or less frequent, you have to scale the CPU usage values accordingly. For example, if you want to have it update every two seconds, you need to edit this line:

               s = s .. " " .. cpu .. ": " .. string.format("%02d", newjiffies-jiffies[cpu]) .. "% "

And divide it by the number of seconds between updates:

               s = s .. " " .. cpu .. ": " ..  string.format("%02d", (newjiffies-jiffies[cpu])/2) .. "% "

All that needs to be done after this is add the widget to the status bar's list of widgets.