September 21, 2020

soltveit.org

..Geekish..

CPU idle time since boot

cpu idle time

CPU idle time since boot needs to be calculated. All the information you need to calculate the total CPU idle time will be found in the /proc/stats file. All Cpu ticks since boot have been accounted for in the following categories: user, nice, system, idle, iowait, IRQ, and softirq. If we add all those, we have all CPU ticks since last time it was booted.

First, we need to add all the numbers:

Total_use = user + nice + system + idle + iowait + irq + softirq
Total_idle = idle / Total_use * 100

Total_idle will now contain the total idle time in percentage since last boot. Let’s use some real numbers and look at an example. If you use the cat command and look at the /proc/stat file, you will see something like this in the first line: (The first line is the average between all the cores) 

cpu 15206177 12026 5264560 1495772551 1787519 0 89796 0 0 0
Total_use = 15206177 + 12026 + 5264560 + 1495772551 + 1787519 + 89796 = 1518132629
Total_idle = 1495772551 / 1518132629 * 100 = 98.5271327700315 (98.53%)

So in this example, the total CPU idle since last boot is 98.53%.

What are those numbers? In the same order as in the example above:

User: Normal processes in user mode
Nice: Niced processes in user mode
System: Processes in kernel mode
Idle: CPU ticks being idle
Iowait: Waiting for I/O to finish
IRQ: Service interrupts
Softirq: service soft interrupts

Example in C# on how to calculate the Total CPU idle:

int counter = 0;
string[] cpuutil = new string[4];
try {
    using (StreamReader sr = new StreamReader("/proc/stat")) {
        String line = sr.ReadLine();
        string[] numbers = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        foreach (string number in numbers)
        {
            if (counter > 0 && counter< 8) {
                totalUse += Int32.Parse(number);
            }
            counter++;
        }
        idleTime = ((float) Int32.Parse(numbers[4])/(float) totalUse)*100;
        cpuutil[0] = Math.Round(idleTime,2).ToString(CultureInfo.InvariantCulture);
        Console.WriteLine("Total Idle: " + cpuutil[0] +" %");              
    }
} 
catch (Exception ex) {
    Console.WriteLine(ex.Message.ToString());
}

You can read more about /proc on the man pages

You can also learn how to check what Debian version you are running.