#!/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