• 获取进程cpu占用


    #!/usr/bin/env python
    import math
    import time

    while 1:
    #########time1
            total1_cpu = []
            total2_cpu = []
            with open('/proc/[pid]/stat','r') as f:
                context = f.readline().split(' ')

            with open('/proc/stat','r') as f:
                    context_total = f.readline()


            for item in context_total.split(' ')[2:]:
                    total1_cpu.append(eval(item))
            total_cpu_sum1 = sum(total1_cpu)

            user_cpu1 = float(context[13])
            sys_cpu1 = float(context[14])
            cutime1 = float(context[15])
            cstime1 = float(context[16])
            process_total_time1 = user_cpu1 + sys_cpu1 + cutime1 + cstime1

    #print(total_cpu_sum1,user_cpu1,sys_cpu1)

            time.sleep(1)

    #########time2

            with open('/proc/6443/stat','r') as f:
                    context = f.readline().split(' ')

            with open('/proc/stat','r') as f:
                    context_total = f.readline()

            for item in context_total.split(' ')[2:]:
                    total2_cpu.append(eval(item))
            total_cpu_sum2 = sum(total2_cpu)

            user_cpu2 = float(context[13])
            sys_cpu2 = float(context[14])
            cutime2 = float(context[15])
            cstime2 = float(context[16])
            process_total_time2 = user_cpu2 + sys_cpu2 + cutime2 + cstime2

            cpu_usage = ((process_total_time2 - process_total_time1)/(total_cpu_sum2 - total_cpu_sum1)) * 100 * 2  # *2 The number of CPUs
            print("%.2f"%cpu_usage)

    参考:http://blog.csdn.net/cybertan/article/details/7596633

            http://www.linuxhowtos.org/manpages/5/proc.htm

  • 相关阅读:
    jquery1.9之学习笔记
    ERROR: Removing 'hello': Device or resource busy
    windows虚拟机性能调整
    kvm虚拟机控制台登录配置
    KVM虚拟机的管理
    window kvm 虚拟机的创建
    kvm虚拟化环境的搭建
    C实现哈希表
    哲学家就餐问题 C语言实现
    Linux面试题
  • 原文地址:https://www.cnblogs.com/guoqp/p/6370061.html
Copyright © 2020-2023  润新知