1+ #!/usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+
4+ '''
5+ Created on 2015年1月28日
6+
7+ @author: xuxu
8+ '''
9+
10+ #需要安装pychartdir模块,http://blog.csdn.net/gb112211/article/details/43272049
11+
12+ import string
13+
14+ from scriptUtils import utils
15+ from pychartdir import *
16+
17+ PATH = lambda p : os .path .abspath (p )
18+
19+ #打开待测应用,运行脚本,默认times为20次(可自己手动修改次数),获取该应用cpu、memory占用率的曲线图,图表保存至chart目录下
20+
21+ #top次数
22+ times = 20
23+
24+ #设备当前运行应用的包名
25+ pkg_name = utils .get_current_package_name ()
26+
27+ #获取cpu、mem占用
28+ def top ():
29+ cpu = []
30+ mem = []
31+
32+ top_info = utils .shell ("top -n %s | %s %s$" % (str (times ), utils .find_util , pkg_name )).stdout .readlines ()
33+
34+ for info in top_info :
35+ temp_list = del_space (info )
36+ cpu .append (temp_list [2 ])
37+ mem .append (temp_list [6 ])
38+
39+ return (cpu , mem )
40+
41+ #去除top信息中的空格,便于获取cpu、mem的值
42+ def del_space (str ):
43+ temp_list1 = str .split (" " )
44+ temp_list2 = []
45+
46+ for str in temp_list1 :
47+ if str != "" :
48+ temp_list2 .append (str )
49+
50+ return temp_list2
51+
52+ #绘制线性图表,具体接口的用法查看ChartDirecto的帮助文档
53+ def line_chart ():
54+ data = top ()
55+ cpu_data = []
56+ mem_data = []
57+
58+ #去掉cpu占用率中的百分号,并转换为int型
59+ for cpu in data [0 ]:
60+ cpu_data .append (string .atoi (cpu .split ("%" )[0 ]))
61+
62+ #去掉内存占用中的单位K,并转换为int型,以M为单位
63+ for mem in data [1 ]:
64+ mem_data .append (string .atof (mem .split ("K" )[0 ])/ 1024 )
65+
66+ #横坐标
67+ labels = []
68+ for i in range (1 , times + 1 ):
69+ labels .append (str (i ))
70+
71+ #自动设置图表区域宽度
72+ if times <= 50 :
73+ xArea = times * 40
74+ elif 50 < times <= 90 :
75+ xArea = times * 20
76+ else :
77+ xArea = 1800
78+ c = XYChart (xArea , 800 , 0xCCEEFF , 0x000000 , 1 )
79+ c .setPlotArea (60 , 100 , xArea - 100 , 650 )
80+ c .addLegend (50 , 30 , 0 , "arialbd.ttf" , 15 ).setBackground (Transparent )
81+
82+ c .addTitle ("cpu and memery info(%s)" % pkg_name , "timesbi.ttf" , 15 ).setBackground (0xCCEEFF , 0x000000 , glassEffect ())
83+ c .yAxis ().setTitle ("The numerical" , "arialbd.ttf" , 12 )
84+ c .xAxis ().setTitle ("Times" , "arialbd.ttf" , 12 )
85+
86+ c .xAxis ().setLabels (labels )
87+
88+ #自动设置X轴步长
89+ if times <= 50 :
90+ step = 1
91+ else :
92+ step = times / 50 + 1
93+
94+ c .xAxis ().setLabelStep (step )
95+
96+ layer = c .addLineLayer ()
97+ layer .setLineWidth (2 )
98+ layer .addDataSet (cpu_data , 0xff0000 , "cpu(%)" )
99+ layer .addDataSet (mem_data , 0x008800 , "mem(M)" )
100+
101+ path = PATH ("%s/chart" % os .getcwd ())
102+ if not os .path .isdir ("%s/chart" % PATH (os .getcwd ())):
103+ os .makedirs (path )
104+
105+ #图标保存至脚本当前目录的chart目录下
106+ c .makeChart (PATH ("%s/%s.png" % (path , utils .timestamp ())))
107+
108+ if __name__ == "__main__" :
109+ print "Starting get top information..."
110+ line_chart ()
111+
112+
113+
114+
0 commit comments