Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

/proc/stat shows ticks for user, nice, sys, idle, iowait, irq and sirq like this:

cpu 6214713 286 1216407 121074379 260283 253506 197368 0 0 0

How can I calculate the individual utilizations (in %) for user, nice etc with these values? Like the values that shows in 'top' or 'vmstat'.

like image 638
jgr Avatar asked Sep 04 '11 10:09

jgr


1 Answers

This code calculates user utilization spread over 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()
like image 73
jgr Avatar answered Sep 30 '22 02:09

jgr