zoukankan      html  css  js  c++  java
  • 获取进程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

  • 相关阅读:
    A visual proof that neural nets can compute any function 2
    Matrix
    Formula
    ID and CLASS
    hugeng007_diary01_the living way
    the mathematical knowledge
    sys.argv[]
    The Convolutional Networks
    DVWA之XSS (跨站脚本攻击)存储型+反射型。
    DVWA之 File Inclusion 文件包含
  • 原文地址:https://www.cnblogs.com/guoqp/p/6370061.html
Copyright © 2011-2022 走看看