引言

利用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. Linux操作命令(六)

    本次实验将介绍 Linux 命令中 wc 和 grep 命令的用法. wc grep 1.wc wc命令是一个统计的工具,主要用来显示文件所包含的行.字和字节数. wc命令是word count的缩写 ...

  2. HDU 4888 Redraw Beautiful Drawings

    网络流. $s$向每一个$r[i]$连边,容量为$r[i]$. 每一个$r[i]$向每一个$c[j]$连边,容量为$k$. 每一个$c[j]$向$t$连边容量为$c[j]$. 跑最大流,中间每一条边上 ...

  3. 洛谷P3391文艺平衡树(Splay)

    题目传送门 转载自https://www.cnblogs.com/yousiki/p/6147455.html,转载请注明出处 经典引文 空间效率:O(n) 时间效率:O(log n)插入.查找.删除 ...

  4. js判断上传图片宽高及文件大小

    <input id="file" type="file"> <input id="Button1" type=" ...

  5. Codeforces Round #165 (Div. 1) Greenhouse Effect(DP)

    Greenhouse Effect time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  6. 图形管线之旅 Part 1

    原文:<A trip through the Graphics Pipeline 2011> 翻译:往昔之剑   转载请注明出处   你可以找到很多PC图形栈的功能描述,但是通常却不明所以 ...

  7. 五种常用的C/C++编译器对64位整型的支持

    变量定义 输出方式 gcc(mingw32) g++(mingw32) gcc(linux i386) g++(linux i386) MicrosoftVisual C++ 6.0 long lon ...

  8. hdu 5592 ZYB's Premutation (权值线段树)

    最近在线段树的世界里遨游,什么都能用线段树做,这不又一道权值线段树了么. ZYB's Premutation Time Limit: 2000/1000 MS (Java/Others)    Mem ...

  9. 【最小生成树】【kruscal】【贪心】CDOJ1636 梦后楼台高锁,酒醒帘幕低垂

    首先,考虑到,我们需要找到一条路径,使它的最小边尽量大,最大边尽量小 然后,考虑到m比较小,我们可以去寻找一个m^2或者m^2logm的算法 考虑枚举最小边,那么我们就需要在m或者mlogm的时间内找 ...

  10. python学习第九十天:vue补习2

    Vue 八.重要指令 v-bind <!-- 值a --> <div v-bind:class='"a"'></div> <!-- 变量a ...