Lua: Get CPU Load on Linux

On May 2, 2011, in Code Monkey, by Tom

Here’s a Lua function that returns the percentage of CPU used on Linux. The load includes time in user space and system space. In case you’re curious, I used `top` to get the load for a couple reasons:

  1. It’s installed by default on most distros (as opposed to the sysstat tools).
  2. It gives the idle time in percentage normalized to 100% (as opposed to /proc/stat which requires knowledge of the jiffy’s interval, which can vary).
function cpu_load(interval)
   interval = interval or 1
   local f = io.popen('top -bp$$ -d ' .. interval .. ' -n 2')
   local s = f:read('*all')

   -- Find the idle times in the stdout output
   local tokens = s:gmatch(',%s*([%d%.]+)%%%s*id')

   -- We're interested in the 2nd 'top' idle time
   local ii = 1
   for idle in tokens do
      if ii == 2 then
         return 100.0 - tonumber(idle)
      end
      ii = ii + 1
   end
end

You can call it from the Lua shell as:

> load = cpu_load()
> print(load)
43.7

Tagged with:  

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>