How to calculate CPU % based on raw CPU ticks in SNMP

Since these are absolute counters, you would have to regularly retrieve these metrics and then do the calculation yourself. So, if you want the number over the next minute, you would have to get the numbers, wait a minute, and get the numbers again. SNMP would not update those numbers too often so you may not be able to get these every second anyway.

Once you have the raw user, nice, system, idle, interrupts counters you can get the total number of ticks by summing these up. Even the MIB description says that adding them up is expected.

$ snmptranslate -Td .1.3.6.1.4.1.2021.11.52
UCD-SNMP-MIB::ssCpuRawSystem
...
    This object may sometimes be implemented as the
    combination of the 'ssCpuRawWait(54)' and
    'ssCpuRawKernel(55)' counters, so care must be
    taken when summing the overall raw counters."

Then, regardless of how long it has been since you took the measurements, the total number of ticks over that period is total1 - total0. And the idle percentage would be (idle1-idle0)/(total1-total0).

You are asking "how do you know how many ticks per second it is typically" but as you can see, you don't need to know that.


Since most of the Linux distros have the 1/100 ticks, a very simple way to do it is via bash:

[myhost]# echo "scale=2; -1 * (`snmpget -Oqv -v2c -c public localhost .1.3.6.1.4.1.2021.11.54.0;sleep 5` - `snmpget -Oqv -v2c -c public localhost .1.3.6.1.4.1.2021.11.54.0` )/`snmpwalk -Oqu -v2c -c public localhost 1.3.6.1.2.1.25.3.3.1.2 | wc -l`/5" | bc | sed 's/^\./0./' | awk '{print "CPU_IOWAIT% " $1}'

IOWAIT 0.07

[myhost]#

On RH/Centos and Ubuntu, it works well and precisely for 5 secs interval... Less than that, snmp does not increment the Counter32, and you get zeroes all the time.

I have done loops and compared with iostat -c 5 100, also generating IO with dd, and it worked well.

You can use any of the ssCPUraw OIDs (1.3.6.1.4.1.2021.11.5x from 50 to 57, if I am not wrong, in my example I have used ssCPURawWait, 54), and the 1.3.6.1.2.1.25.3.3.1.2 | wc -l is to get the number of cores...

You need to divide the "delta" of the counter / interval - in my case, 5 / - this is basically what the script does!


In addition to what has been already written by chutz, the reference to the duration of a tick can be found in man 2 times:

The number of clock ticks per second can be obtained using:

     sysconf(_SC_CLK_TCK);

which is a system function to be called in C but also can be obtained by simply running getconf CLK_TCK in your shell. This number is a compile-time constant and could be changed by anyone touching the source files, but this would be a rather rare event - common Linux distros all come with the value 100.

For example:

$ getconf CLK_TCK
100