欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

Python监控进程性能数据并绘图保存为PDF文档

程序员文章站 2022-04-18 14:06:07
...

引言

利用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 


输出结果示范图

Python监控进程性能数据并绘图保存为PDF文档