开发者

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

开发者 https://www.devze.com 2023-04-02 02:15 出处:网络
/proc/stat shows ticks for user, nice, sys, idle, iowait, irq and sirq like this: cpu6214713 286 1216407 121074379 260283 253506 1973开发者_运维百科68 0 0 0

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

cpu 6214713 286 1216407 121074379 260283 253506 1973开发者_运维百科68 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'.


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()


From Documentation/filesystems/proc.txt:

(...) These numbers identify the amount of time the CPU has spent performing different kinds of work. Time units are in USER_HZ (typically hundredths of a second).

So to figure out utilization in terms of percentages you need to:

  • Find out what USER_HZ is on the machine
  • Find out how long it's been since the system booted.

The second one is easy: there is a btime line in that same file which you can use for that. For USER_HZ, check out How to get number of mili seconds per jiffy.

0

精彩评论

暂无评论...
验证码 换一张
取 消