Python监控进程性能数据并绘图保存为PDF文档
引言
利用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()
输出结果示范图

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Ollama is a super practical tool that allows you to easily run open source models such as Llama2, Mistral, and Gemma locally. In this article, I will introduce how to use Ollama to vectorize text. If you have not installed Ollama locally, you can read this article. In this article we will use the nomic-embed-text[2] model. It is a text encoder that outperforms OpenAI text-embedding-ada-002 and text-embedding-3-small on short context and long context tasks. Start the nomic-embed-text service when you have successfully installed o

Performance comparison of different Java frameworks: REST API request processing: Vert.x is the best, with a request rate of 2 times SpringBoot and 3 times Dropwizard. Database query: SpringBoot's HibernateORM is better than Vert.x and Dropwizard's ORM. Caching operations: Vert.x's Hazelcast client is superior to SpringBoot and Dropwizard's caching mechanisms. Suitable framework: Choose according to application requirements. Vert.x is suitable for high-performance web services, SpringBoot is suitable for data-intensive applications, and Dropwizard is suitable for microservice architecture.

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values takes a relatively long time.

Effective techniques for optimizing C++ multi-threaded performance include limiting the number of threads to avoid resource contention. Use lightweight mutex locks to reduce contention. Optimize the scope of the lock and minimize the waiting time. Use lock-free data structures to improve concurrency. Avoid busy waiting and notify threads of resource availability through events.

View Go function documentation using the IDE: Hover the cursor over the function name. Press the hotkey (GoLand: Ctrl+Q; VSCode: After installing GoExtensionPack, F1 and select "Go:ShowDocumentation").

The performance of different PHP functions is crucial to application efficiency. Functions with better performance include echo and print, while functions such as str_replace, array_merge, and file_get_contents have slower performance. For example, the str_replace function is used to replace strings and has moderate performance, while the sprintf function is used to format strings. Performance analysis shows that it only takes 0.05 milliseconds to execute one example, proving that the function performs well. Therefore, using functions wisely can lead to faster and more efficient applications.

Static function performance considerations are as follows: Code size: Static functions are usually smaller because they do not contain member variables. Memory occupation: does not belong to any specific object and does not occupy object memory. Calling overhead: lower, no need to call through object pointer or reference. Multi-thread-safe: Generally thread-safe because there is no dependence on class instances.

In PHP, the conversion of arrays to objects will have an impact on performance, mainly affected by factors such as array size, complexity, object class, etc. To optimize performance, consider using custom iterators, avoiding unnecessary conversions, batch converting arrays, and other techniques.
