用python绘制cpu曲线

周末没事画个cpu曲线

热心网友们都不给力,也没个例子给参考下子

先上代码

#encoding=utf-8
import  os,time,re
import matplotlib.pyplot as plt
import sys

begin = time.time()
pattern = re.compile("\d+")
time2sleep = 2.5
x = []
y = []
t = 0
totaltime =float(sys.argv[1]) if len(sys.argv)>1 else 10.0
print totaltime
while totaltime>=0:
#    cpuInfo =  os.popen('top -bi -n 2 -d 0.01').read().split('\n\n\n')[1].split('\n')[2]
#    items = pattern.findall(cpuInfo)
#    usage =float(items[0]) +float(items[1])+float(items[2])
#    top巨慢,果断直接从/proc/stat搞起    
    
    info1 = os.popen("cat /proc/stat").readline()
    ct1 = pattern.findall(info1)
    sum1 = 0
    for i in ct1:
        sum1 += int(i)
   
    time.sleep(0.1) 

    info2 = os.popen("cat /proc/stat").readline()
    ct2 = pattern.findall(info2)
    sum2 = 0
    for i in ct2:
        sum2 += int(i)
   
    usage = (int(ct2[0])+int(ct2[2])-int(ct1[0])-int(ct1[2]))*1.0/(sum2-sum1)*100
    print usage,"%"
    y.append(usage)
   
    now = time.time()-begin
    x.append(now)
    
    totaltime = totaltime - 0.1

end = time.time()

print (end-begin)
plt.plot(x,y)
plt.title("CPU Usage Rate")
plt.xlabel("time/s")
plt.ylabel("percentage/%")

plt.show()

其中sys.popen用来执行shell命令,和sys.system的区别是,system会直接打印信息而popen会返回信息的对象

re模块,用正则表达式提取/proc/stat中的数字,其中正则部分可以参考谷歌教程

CPU利用率通过/proc/stat提供的数据进行计算

 

其中计算的公式参考这里,解释的很清楚,主要是因为执行top实在是有点慢

最后用matplotlib模块绘图,本来是想画实时的,但一画图过后,程序就中断了,改日再想想办法

绘图示例的可以参考这里,其实和matlab画差不多

最后来张结果图

图片略丑,各位不要嫌弃啊,明天又要滚去学校了,诶。。。

 

 

posted on 2013-04-14 19:03  luckistmaomao  阅读(2299)  评论(0编辑  收藏  举报

导航