Probe average cpu utilisation (MRTG)

There are two main tools to keep track of your CPU usage: top and vmstat.

  • top is an interactive tool: it shows you the CPU usage of each process, as well as overall statistics, updated every 5 seconds. It’s good for hands-on checking.

    #top 17:18:34 up 2 days, 8:14, 3 users, load average: 0.00, 0.00, 0.00
    47 processes: 46 sleeping, 1 running, 0 zombie, 0 stopped
    CPU states: 0.1% user 0.1% system 0.0% nice 0.0% iowait 99.6% idle
    Mem: 1030872k av, 1022256k used, 8616k free,
    0k shrd, 104844k buff
    777088k actv, 12k in_d, 22296k in_c
    Swap: 2048276k av, 8120k used, 2040156k free
    640080k cached
    PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME CPU COMMAND
    30776 root 19 0 1140 1140 852 R 0.9 0.1 0:00 0 top
    1 root 15 0 504 464 436 S 0.0 0.0 0:03 0 init (...)

    But say you want to get just one number (percentage) back, so you can use it for logging.
  • vmstat wil give you the following output:

    #vmstat
    procs memory swap io system cpu
    r b w swpd free buff cache si so bi bo in cs us sy id
    0 0 0 7964 8804 104712 640224 0 0 2 16 129 27 0 0 100

    You can run vmstat 1 5 to get 5 consecutive measurements (1 second apart). The number we want is the average CPU usage, or (100% – idle). The following command will do the job:
    #vmstat 1 5 | gawk "/0/ {tot=tot+1; id=id+$16} END {print 100 - id/tot}"
    gives
    0.4

1 thought on “Probe average cpu utilisation (MRTG)”

  1. As vmstat manpage says, in the “continuous report with delay” mode “… the first report given is the average of the statistics since system boot”. So the command above will give wrong number if we don’t skip the first result.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.