Calculation of Process cpu Usage

  java

computational formula

(process jiffies) * 100.0f / ((float)Hertz * (float)et * cpuCoresCount)

Or

(process jiffies) * 100.0f / (float)Hertz / (float)et / cpuCoresCount

Or

100 * (process jiffies)/ (float)Hertz / (float)et  / cpuCoresCount

Equivalent to %CPU value in top-pid

Calculation of process jiffies

Process jiffies is the jiffies provided by the kernel that the process consumes in DeltaT time. Specifically, the 14th-14-17 token of the /proc/<pid>/stat file. 14-17 tokens are respectively utime, stime, cutime, cstime. Cutime/cstime are jiffies consumed by the child processes of the process spawn in user state and kernel state respectively.

process jiffies = utime + stime + cutime + cstime

Jiffies is the Linux kernel variable (unsigned long), which is used to record how many tick have passed since the system was turned on. Every time timer interrupt occurs, the Jiffies variable is incremented by one.

Note that jiffies in stat is an absolute cumulative value, so two time points should be taken to calculate the jiffies consumed in DeltaT.

(process jiffies) = (current process jiffies) – (last process jiffies)

Hertz(tick per second)

What is jiffies? In fact, it is a time unit defined by Linux kernel, and the value is 1/Hertz. In Linux kernel, the unit of time consumed by processes/threads is this jiffies.

Hertz is CLK_TCK and can be obtained from getconf CLK_TCK.

The clock frequency of LINUX system is determined by a constant HZ, usually Hz = 100, i.e. 100Hz, and one cycle is 1/100 s = 10ms = 10 7 ns, so its accuracy is 10 ms (milliseconds). That is to say, there is an interruption every 10ms. So generally speaking, the accuracy of Linux is 10 milliseconds.

et

Here is the interval time for each statistic, in seconds.

(System.nanoTime() – lastNanoTime) * 1E-9

Cpu cores

/usr/bin/nproc

Or ..

cat /proc/cpuinfo | grep processor | wc -l

doc