Computing user, nice, sys, idle, iowait, irq and sirq from / proc / stat

/ proc / stat shows the ticks for the user, nice, sys, idle, iowait, irq and sirq as follows:

cpu 6214713 286 1216407 121074379 260283 253506 197368 0 0 0

How can I calculate individual usage (in%) for user, nice, etc. with these values? Similar to the values ​​that appear in 'top' or 'vmstat'.

+7
source share
2 answers

From Documentation/filesystems/proc.txt :

(...) These numbers determine the time taken by the CPU for various types of work. The time units are in USER_HZ (usually hundredths of a second).

So, to determine percent use, you need to:

  • Find out what's on USER_HZ
  • Find out how much time has passed since the system started.

The second is easy: there is a btime line in the same file that you can use for this. For USER_HZ check How to get the number of seconds of a mile at a time .

+4
source

This code calculates the distribution of user usage across all cores.

 import os import time import multiprocessing def main(): jiffy = os.sysconf(os.sysconf_names['SC_CLK_TCK']) num_cpu = multiprocessing.cpu_count() stat_fd = open('/proc/stat') stat_buf = stat_fd.readlines()[0].split() user, nice, sys, idle, iowait, irq, sirq = ( float(stat_buf[1]), float(stat_buf[2]), float(stat_buf[3]), float(stat_buf[4]), float(stat_buf[5]), float(stat_buf[6]), float(stat_buf[7]) ) stat_fd.close() time.sleep(1) stat_fd = open('/proc/stat') stat_buf = stat_fd.readlines()[0].split() user_n, nice_n, sys_n, idle_n, iowait_n, irq_n, sirq_n = ( float(stat_buf[1]), float(stat_buf[2]),. float(stat_buf[3]), float(stat_buf[4]), float(stat_buf[5]), float(stat_buf[6]), float(stat_buf[7]) ) stat_fd.close() print ((user_n - user) * 100 / jiffy) / num_cpu if __name__ == '__main__': main() 
+10
source

All Articles