引言
利用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和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版
中文版,非常好用

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),