引言

利用psutil模块(https://pypi.python.org/pypi/psutil/),可以很方便的监控系统的CPU、内存、磁盘IO、网络带宽等性能參数,下面是否代码为监控某个特定程序的CPU资源消耗。打印监控数据,终于画图显示,而且保存为指定的 PDF
文档备份。

示范代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2015 By Thomas Hu. All rights reserved. @author : Thomas Hu (thomashtq#163.com)
@version: 1.0
@created: 2015-7-14
'''
import matplotlib.pyplot as plt
import psutil as ps
import os
import time
import random
import collections
import argparse class ProcessMonitor(object):
def __init__(self, key_name, fields, duration, interval):
self.key_name = key_name
self.fields = fields
self.duration = float(duration)
self.inveral = float(interval) self.CPU_COUNT = ps.cpu_count()
self.MEM_TOTAL = ps.virtual_memory().total / (1024 * 1024)
self.procinfo_dict = collections.defaultdict(dict) def _get_proc_info(self, pid):
try:
proc = ps.Process(pid)
name = proc.name()
# If not contains the key word, return None
if name.find(self.key_name) == -1:
return None
pinfo = {
"name": name,
"pid" : pid,
}
# If the field is correct, add it to the process information dictionary.
for field in self.fields:
if hasattr(proc, field):
if field == "cpu_percent":
pinfo[field] = getattr(proc, field)(interval = 0.1) / self.CPU_COUNT
elif field == "memory_percent":
pinfo[field] = getattr(proc, field)() * self.MEM_TOTAL / 100
else:
pinfo[field] = getattr(proc, field)()
if pid not in self.procinfo_dict:
self.procinfo_dict[pid] = collections.defaultdict(list)
self.procinfo_dict[pid]["name"] = name
for field in self.fields:
self.procinfo_dict[pid][field].append(pinfo.get(field, 0))
print(pinfo)
return pinfo
except:
pass
return None def monitor_processes(self):
start = time.time()
while time.time() - start < self.duration:
try:
pids = ps.pids()
for pid in pids:
self._get_proc_info(pid)
except KeyboardInterrupt:
print("Killed by user keyboard interrupted!")
return def _get_color(self):
color = "#"
for i in range(3):
a = hex(random.randint(0, 255))[2:]
if len(a) == 1:
a = "0" + a
color += a
return color.upper() def draw_figure(self, field, pdf):
# Draw each pid line
for pid in self.procinfo_dict:
x = range(len(self.procinfo_dict[pid][field]))
#print x, self.procinfo_dict[pid][field]
plt.plot(x, self.procinfo_dict[pid][field], label = "pid" + str(pid), color = self._get_color())
plt.xlabel(time.strftime("%Y-%m-%d %H:%M:%S"))
plt.ylabel(field.upper())
plt.title(field + " Figure")
plt.legend(loc = "upper left")
plt.grid(True)
plt.savefig(pdf, dpi = 200)
plt.show() def Main():
parser = argparse.ArgumentParser(description='Monitor process CPU and Memory.')
parser.add_argument("-k", dest='key', type=str, default="producer",
help='the key word of the processes to be monitored(default is "producer")')
parser.add_argument("-d", dest='duration', type=int, default=60,
help='duration of the monitor to run(unit: seconds, default is 60)')
parser.add_argument('-i', dest='interval', type=float, default=1.0,
help='interval of the sample(unit: seconds, default is 1.0)')
args = parser.parse_args()
fields = ["cpu_percent", "memory_percent"]
#print args.key, args.duration, args.interval
pm = ProcessMonitor(args.key, fields, args.duration, args.interval)
pm.monitor_processes()
pm.draw_figure("cpu_percent", "cpu.pdf")
pm.draw_figure("memory_percent", "mem.pdf") if __name__ == "__main__":
Main()

输出结果示范图

Python监控进程性能数据并画图保存为PDF文档的更多相关文章

  1. ABBYY FineReader 15 中保存和导出PDF文档的小细节

    运用ABBYY FineReader OCR文字识别软件,用户能将各种格式的PDF文档保存为新的PDF文档.PDF/A格式文档,以及Microsoft Word.Excel.PPT等格式.在保存与导出 ...

  2. 使用Jyhon脚本和PMI模块监控WAS性能数据

    使用Jyhon脚本和PMI模块监控WAS性能数据的优点有: 1.可以使用非交互的方式远程获取数据 2.不需要图形化模块支持 3.对各种was版本的兼容性较高 4.使用方便,官方自带 缺点也有很多: 1 ...

  3. Python进阶----进程间数据隔离, join阻塞等待, 进程属性, 僵尸进程和孤儿进程, 守护进程

    Python进阶----进程间数据隔离, join阻塞等待, 进程属性, 僵尸进程和孤儿进程, 守护进程 一丶获取进程以及父进程的pid 含义:    进程在内存中开启多个,操作系统如何区分这些进程, ...

  4. Python处理Excel和PDF文档

    一.使用Python操作Excel Python来操作Excel文档以及如何利用Python语言的函数和表达式操纵Excel文档中的数据. 虽然微软公司本身提供了一些函数,我们可以使用这些函数操作Ex ...

  5. 程序生成word与PDF文档的方法(python)

    程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用free ...

  6. python爬虫处理在线预览的pdf文档

    引言 最近在爬一个网站,然后爬到详情页的时候发现,目标内容是用pdf在线预览的 比如如下网站: https://camelot-py.readthedocs.io/en/master/_static/ ...

  7. 将mat文件中的数据按要求保存到txt文档中(批处理)

    之前有个老朋友,让帮忙将一个mat中的数据重新保存到txt中,由于数据比较多需要用到批处理,之前弄过很多次,但每次一到要用的时候总是忘记怎么写了,现在记录一下,免得后面老是需要上网搜.这里先说一个比较 ...

  8. python实用小技能分享,教你如何使用 Python 将 pdf 文档进行 加密 解密

    上次说了怎么将word转换为pdf格式 及 实现批量将word转换为pdf格式(点击这里),这次我又get到一个新技能–使用 Python 将 pdf 文档进行 加密 解密,哈哈哈 希望帮到更多人! ...

  9. 利用Python将PDF文档转为MP3音频

    1. 转语音工具 微信读书有一个功能,可以将书里的文字转换为音频,而且声音优化的不错,比传统的机械朗读听起来舒服很多. 记得之前看到过Python有一个工具包,可以将文字转换为语音,支持英文和中文,而 ...

随机推荐

  1. Aizu 2784 Similarity of Subtrees(树哈希)

    Similarity of Subtrees Define the depth of a node in a rooted tree by applying the following rules r ...

  2. Beaglebone Black教程Beaglebone Black的引脚分配

    Beaglebone Black教程Beaglebone Black的引脚分配 Beaglebone Black的引脚分配 绝大多数的微型开发平台都提供了一些称为GPIO的输入输出端口.这些端口可以让 ...

  3. Sd - Hibernate

    Sd - Hibernate 附:http://blog.csdn.net/ta8210/article/details/1582162 数据库连接池实现原理 http://hi.baidu.com/ ...

  4. luogu P1047 校门外的树

    题目描述 某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米.我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置:数轴上的每个整数点,即0,1,2,……,L,都种 ...

  5. BZOJ 3790 神奇项链(manacher+DP+树状数组)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3790 [题目大意] 问最少用几个回文串可以构成给出串,重叠部分可以合并 [题解] 我们 ...

  6. python基础之数据类型之数字、字符串、列表

    数据类型及内置方法 一.数字类型 整数型(int) 1.用途:年龄,号码等 2.定义:age = 10   age = int(10) x = int(’11’)   int只能转换纯数字的字符串 3 ...

  7. Java操作excel表格

    (1)Java读取excel表格 package com.songyan.excel; import java.io.File; import java.io.FileInputStream; imp ...

  8. 使用CURL抓取淘宝页面

    /** * 根据地址抓取淘宝页面html代码 * @param type $url 地址 * @return boolean */ public function getTaoBaoHtml($url ...

  9. [Winform]线程间操作无效,从不是创建控件的线程访问它的几个解决方案,async和await?

    目录 概述 取消跨线程检查 使用委托异步调用 sync和await 总结 概述 最近在qq群里有一朋友,问起在winform中怎么通过开启线程的方式去处理耗时的操作,比如,查看某个目录下所有的文件,或 ...

  10. Fork & vfork & clone (转载)

    转自:http://blog.csdn.net/zqy2000zqy/archive/2006/09/04/1176924.aspx 进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合, ...