引言
利用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不是严格的逐行执行,而是基于解释器的机制进行优化和条件执行。解释器将代码转换为字节码,由PVM执行,可能会预编译常量表达式或优化循环。理解这些机制有助于优化代码和提高效率。

可以使用多种方法在Python中连接两个列表:1.使用 操作符,简单但在大列表中效率低;2.使用extend方法,效率高但会修改原列表;3.使用 =操作符,兼具效率和可读性;4.使用itertools.chain函数,内存效率高但需额外导入;5.使用列表解析,优雅但可能过于复杂。选择方法应根据代码上下文和需求。

有多种方法可以合并Python列表:1.使用 操作符,简单但对大列表不内存高效;2.使用extend方法,内存高效但会修改原列表;3.使用itertools.chain,适用于大数据集;4.使用*操作符,一行代码合并小到中型列表;5.使用numpy.concatenate,适用于大数据集和性能要求高的场景;6.使用append方法,适用于小列表但效率低。选择方法时需考虑列表大小和应用场景。

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python中,for循环用于遍历可迭代对象,while循环用于条件满足时重复执行操作。1)for循环示例:遍历列表并打印元素。2)while循环示例:猜数字游戏,直到猜对为止。掌握循环原理和优化技巧可提高代码效率和可靠性。

要将列表连接成字符串,Python中使用join()方法是最佳选择。1)使用join()方法将列表元素连接成字符串,如''.join(my_list)。2)对于包含数字的列表,先用map(str,numbers)转换为字符串再连接。3)可以使用生成器表达式进行复杂格式化,如','.join(f'({fruit})'forfruitinfruits)。4)处理混合数据类型时,使用map(str,mixed_list)确保所有元素可转换为字符串。5)对于大型列表,使用''.join(large_li

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver CS6
视觉化网页开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版
SublimeText3 Linux最新版

禅工作室 13.0.1
功能强大的PHP集成开发环境

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。