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()
输出结果示范图

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Ollama は、Llama2、Mistral、Gemma などのオープンソース モデルをローカルで簡単に実行できるようにする非常に実用的なツールです。この記事では、Ollamaを使ってテキストをベクトル化する方法を紹介します。 Ollama をローカルにインストールしていない場合は、この記事を読んでください。この記事では、nomic-embed-text[2] モデルを使用します。これは、短いコンテキストおよび長いコンテキストのタスクにおいて OpenAI text-embedding-ada-002 および text-embedding-3-small よりも優れたパフォーマンスを発揮するテキスト エンコーダーです。 o が正常にインストールされたら、nomic-embed-text サービスを開始します。

PHP の配列キー値の反転メソッドのパフォーマンスを比較すると、array_flip() 関数は、大規模な配列 (100 万要素以上) では for ループよりもパフォーマンスが良く、所要時間が短いことがわかります。キー値を手動で反転する for ループ方式は、比較的長い時間がかかります。

さまざまな Java フレームワークのパフォーマンス比較: REST API リクエスト処理: Vert.x が最高で、リクエスト レートは SpringBoot の 2 倍、Dropwizard の 3 倍です。データベース クエリ: SpringBoot の HibernateORM は Vert.x や Dropwizard の ORM よりも優れています。キャッシュ操作: Vert.x の Hazelcast クライアントは、SpringBoot や Dropwizard のキャッシュ メカニズムよりも優れています。適切なフレームワーク: アプリケーションの要件に応じて選択します。Vert.x は高パフォーマンスの Web サービスに適しており、SpringBoot はデータ集約型のアプリケーションに適しており、Dropwizard はマイクロサービス アーキテクチャに適しています。

C++ マルチスレッドのパフォーマンスを最適化するための効果的な手法には、リソースの競合を避けるためにスレッドの数を制限することが含まれます。競合を軽減するには、軽量のミューテックス ロックを使用します。ロックの範囲を最適化し、待ち時間を最小限に抑えます。ロックフリーのデータ構造を使用して同時実行性を向上させます。ビジー待機を回避し、イベントを通じてリソースの可用性をスレッドに通知します。

IDE を使用して Go 関数のドキュメントを表示する: 関数名の上にカーソルを置きます。ホットキーを押します (GoLand: Ctrl+Q; VSCode: GoExtensionPack をインストールした後、F1 キーを押して「Go:ShowDocumentation」を選択します)。

さまざまな PHP 関数のパフォーマンスは、アプリケーションの効率にとって非常に重要です。パフォーマンスの良い関数には echo や print などがありますが、str_replace、array_merge、file_get_contents などの関数のパフォーマンスは低くなります。たとえば、str_replace 関数は文字列の置換に使用され、中程度のパフォーマンスを発揮しますが、sprintf 関数は文字列の書式設定に使用されます。パフォーマンス分析によると、1 つの例の実行にかかる時間はわずか 0.05 ミリ秒であり、関数が適切に実行されることが証明されています。したがって、関数を賢く使用すると、アプリケーションをより高速かつ効率的に実行できます。

Java 関数のパフォーマンスをベンチマークする方法は、Java Microbenchmark Suite (JMH) を使用することです。具体的な手順は次のとおりです。 JMH 依存関係をプロジェクトに追加します。新しい Java クラスを作成し、ベンチマーク メソッドを表す @State アノテーションを付けます。クラス内にベンチマーク メソッドを記述し、 @Benchmark アノテーションを付けます。 JMH コマンド ライン ツールを使用してベンチマークを実行します。

PHP では、配列からオブジェクトへの変換はパフォーマンスに影響を与え、主に配列のサイズ、複雑さ、オブジェクト クラスなどの要因によって影響を受けます。パフォーマンスを最適化するには、カスタム反復子の使用、不必要な変換の回避、配列のバッチ変換などの手法を検討してください。
