引言利用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 pltimport psutil as psimport osimport timeimport randomimport collectionsimport argparseclass 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()
输出结果示范图
