随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

获取单个程序CPU使用情况趋势图

本文定位:已将CPU历史数据存盘,等待可视化进行分析,可暂时没有思路。
前面一篇文章(http://www.cnblogs.com/MikeZhang/archive/2012/02/01/cpuRatePythonTop.html)提到过在linux下如何用
python将top命令的结果进行存盘,本文是它的后续。

python中我们可以用matplotlib很方便的将数据可视化,比如下面的代码:

1 import matplotlib.pyplot as plt
2
3 list1 = [1,2,3]
4 list2 = [4,5,9]
5 plt.plot(list1,list2)
6 plt.show()

执行效果如下:

上面只是给plot函数传了两个list数据结构,show一下图形就出来了……哈哈,很方便吧!
获取CPU趋势图就用这个了!
可我们现在得到的数据没那么友好,比如我现在有个文件(file.txt),内容如下:

1328503984 Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328503997 Cpu(s): 7.7%us, 7.7%sy, 0.0%ni, 76.9%id, 0.0%wa, 0.0%hi, 7.7%si, 0.0%st
1328504000 Cpu(s): 0.0%us, 9.1%sy, 0.0%ni, 90.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328504012 Cpu(s): 9.1%us, 0.0%sy, 0.0%ni, 90.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328504016 Cpu(s): 8.3%us, 8.3%sy, 0.0%ni, 83.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328504019 Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328504022 Cpu(s): 0.0%us, 9.1%sy, 0.0%ni, 90.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
1328504228 Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st

其中,第一列为时间,第六列为CPU的idle值。

要从这组数据中得出CPU使用情况趋势图,我们就要做些工作了。

下面是代码,这里提供一个思路,需要的朋友拷回去改一下吧:

复制代码
 1 #coding:utf-8
2 '''
3 File : cpuUsage.py
4 Author : Mike
5 E-Mail : Mike_Zhang@live.com
6 '''
7 import matplotlib.pyplot as plt
8 import string
9
10 def getCpuInfData(fileName):
11 ret = {}
12 f = open(fileName,"r")
13 lineList = f.readlines()
14 for line in lineList:
15 tmp = line.split()
16 sz = len(tmp)
17 t_key = string.atoi(tmp[0]) # 得到key
18 t_value = 100.001-string.atof(line.split(':')[1].split(',')[3].split('%')[0]) # 得到value
19 print t_key,t_value
20 if not ret.has_key(t_key) :
21 ret[t_key] = []
22 ret[t_key].append(t_value)
23 f.close()
24 return ret
25
26 retMap1 = getCpuInfData("file.txt")
27 # 生成CPU使用情况趋势图
28 list1 = retMap1.keys()
29 list1.sort()
30 list2 = []
31 for i in list1:list2.append(retMap1[i])
32 plt.plot(list1,list2)
33 plt.show()
复制代码

好,就这些了,希望对你有帮助。

posted on   Mike_Zhang  阅读(1161)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2012年2月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 1 2 3
4 5 6 7 8 9 10

点击右上角即可分享
微信分享提示