您的位置:首页 > 编程语言 > Python开发

Python绘制CPU曲线图

2015-07-12 09:54 633 查看
使用Python绘图工具库,处理和分析系统资源使用情况(本文以CPU使用率为例),且作记录。

1. 工具安装

安装python(此处用的是2.7)及相应的库:matplotlib(windows下需装dateutil、pyparsing、scipy)、numpy;

2. 获取数据

获取进程CPU使用率:

top -d 1 | grep 'test' | grep -v 'grep' >> /tmp/tmp_cpu.log

awk '{print $9}' /tmp/tmp_cpu.log >> /tmp/log/test_cpu.log

3. python绘图

python draw.py test /tmp/log

# -*- coding:utf-8 -*-

import matplotlib.pyplot as pl
import numpy as np
import os
import string
import sys

def set_plot_attr(plt, title, xlabel, ylabel):
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
plt.legend()
pl.subplots_adjust(wspace=0.5, hspace=0.5)

def draw_cpu(pro, rootdir):
pro = sys.argv[1]
rootdir = sys.argv[2]
mean_data = []
files = os.listdir(rootdir)
for file in files:
data = []
f = open(rootdir + '/' + file, 'r')
for line in f.readlines():
data.append(string.atof(line.strip()))
f.close()
pl.subplot(211)
pl.plot(data, label=file)
mean_data.append(np.mean(data))

set_plot_attr(pl, pro + ' CPU Usage', 'Time (s)', 'CPU Usage (%)')
pl.subplot(212)
pl.plot(mean_data)
set_plot_attr(pl, pro + ' Mean CPU Usage', 'Time (s)', 'CPU Usage (%)')
pl.show()

def usage():
print 'Usage: draw.py pro rootdir'
print '       pro: progress name'
print '       rootdir: log file directory'

if __name__ == '__main__':
try:
draw_cpu(sys.argv[1], sys.argv[2])
except:
usage()


测试三组数据,结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: