目录
引言
示范代码
输出结果示范图
首页 后端开发 Python教程 Python监控进程性能数据并绘图保存为PDF文档

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

Jun 06, 2016 am 11:14 AM
性能 文档 进程

引言

利用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=&#39;Monitor process CPU and Memory.&#39;)
    parser.add_argument("-k", dest=&#39;key&#39;, type=str, default="producer", 
                   help=&#39;the key word of the processes to be monitored(default is "producer")&#39;)
    parser.add_argument("-d", dest=&#39;duration&#39;, type=int, default=60,
                   help=&#39;duration of the monitor to run(unit: seconds, default is 60)&#39;)
    parser.add_argument(&#39;-i&#39;, dest=&#39;interval&#39;, type=float, default=1.0,
                   help=&#39;interval of the sample(unit: seconds, default is 1.0)&#39;)
    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()
  
    
登录后复制

登录后复制

 

输出结果示范图

\
 

 

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

不同Java框架的性能对比 不同Java框架的性能对比 Jun 05, 2024 pm 07:14 PM

不同Java框架的性能对比:RESTAPI请求处理:Vert.x最佳,请求速率达SpringBoot2倍,Dropwizard3倍。数据库查询:SpringBoot的HibernateORM优于Vert.x及Dropwizard的ORM。缓存操作:Vert.x的Hazelcast客户机优于SpringBoot及Dropwizard的缓存机制。合适框架:根据应用需求选择,Vert.x适用于高性能Web服务,SpringBoot适用于数据密集型应用,Dropwizard适用于微服务架构。

本地运行性能超越 OpenAI Text-Embedding-Ada-002 的 Embedding 服务,太方便了! 本地运行性能超越 OpenAI Text-Embedding-Ada-002 的 Embedding 服务,太方便了! Apr 15, 2024 am 09:01 AM

Ollama是一款超级实用的工具,让你能够在本地轻松运行Llama2、Mistral、Gemma等开源模型。本文我将介绍如何使用Ollama实现对文本的向量化处理。如果你本地还没有安装Ollama,可以阅读这篇文章。本文我们将使用nomic-embed-text[2]模型。它是一种文本编码器,在短的上下文和长的上下文任务上,性能超越了OpenAItext-embedding-ada-002和text-embedding-3-small。启动nomic-embed-text服务当你已经成功安装好o

PHP 数组键值翻转:不同方法的性能对比分析 PHP 数组键值翻转:不同方法的性能对比分析 May 03, 2024 pm 09:03 PM

PHP数组键值翻转方法性能对比表明:array_flip()函数在大型数组(超过100万个元素)下比for循环性能更优,耗时更短。手动翻转键值的for循环方法耗时相对较长。

C++中如何优化多线程程序的性能? C++中如何优化多线程程序的性能? Jun 05, 2024 pm 02:04 PM

优化C++多线程性能的有效技术包括:限制线程数量,避免争用资源。使用轻量级互斥锁,减少争用。优化锁的范围,最小化等待时间。采用无锁数据结构,提高并发性。避免忙等,通过事件通知线程资源可用性。

如何在 IDE 中查看 Golang 函数文档? 如何在 IDE 中查看 Golang 函数文档? Apr 18, 2024 pm 03:06 PM

使用IDE查看Go函数文档:将光标悬停在函数名称上。按下热键(GoLand:Ctrl+Q;VSCode:安装GoExtensionPack后,F1并选择"Go:ShowDocumentation")。

PHP函数的性能如何? PHP函数的性能如何? Apr 18, 2024 pm 06:45 PM

不同PHP函数的性能对应用程序效率至关重要。性能较好的函数包括echo、print,而str_replace、array_merge、file_get_contents等函数性能较慢。例如,str_replace函数用于替换字符串,性能中等,而sprintf函数用于格式化字符串。性能分析表明,执行一个示例仅需0.05毫秒,证明了函数性能良好。因此,明智地使用函数可以构建更快、更高效的应用程序。

C++ 静态函数的性能考虑有哪些? C++ 静态函数的性能考虑有哪些? Apr 16, 2024 am 10:51 AM

静态函数性能考虑如下:代码大小:静态函数通常更小,因为不包含成员变量。内存占用:不属于任何特定对象,不占用对象内存。调用开销:更低,无需通过对象指针或引用调用。多线程安全:通常线程安全,因为不依赖于类实例。

PHP 数组转对象对性能的影响是什么? PHP 数组转对象对性能的影响是什么? Apr 30, 2024 am 08:39 AM

在PHP中,数组到对象的转换会对性能产生影响,主要受数组大小、复杂性、对象类等因素影响。为了优化性能,可以考虑使用自定义迭代器、避免不必要的转换、批量转换数组等技巧。

See all articles