註記:此頁為由 AI(gpt-5-mini-2025-08-07)自動翻譯自英文原文,可能含有少量不準確之處。
📌 介紹
這篇文章介紹 psutil,一個開源的 Python 套件,可提供有關 CPU、記憶體、磁碟與網路的系統資訊。內容涵蓋 psutil 的安裝,並示範用於監控 CPU 與記憶體使用率的實用函式,以及如何使用裝飾器將其整合到 Python 程式碼中。
🚀 快速開始
psutil 中的實用函式
CPU
1 2 3 4
| psutil.cpu_count() psutil.cpu_percent() psutil.cpu_percent(percpu=True) psutil.cpu_percent(interval=1)
|
記憶體
1 2 3 4 5 6 7
| info = psutil.virtual_memory()
info.total / 1024 / 1024 / 1024
info.percent
|
MacOS
Ubuntu
如何將 psutil 整合到我們的程式?
我們可以使用裝飾器來監控每個函式的 CPU 與記憶體使用情況。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import psutil
def monitor(func): def wrapper(*args, **kwargs): process = psutil.Process() cur_func_pid = process.pid process = psutil.Process(cur_func_pid)
func(*args, **kwargs)
cpu_usage = process.cpu_percent(interval=0.01) memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
print(f"CPU usage: {cpu_usage}%") print(f"Memory usage: {memory_usage}GB")
return wrapper
|
範例
1 2 3 4 5 6 7 8
| @monitor def example_code(): import numpy as np
for i in range(100): np.random.rand(100, 100, 100)
example_code()
|
🔁 小結
- psutil 是一個用於系統監控的開源 Python 套件。
- 它提供取得 CPU 與記憶體使用資訊的實用函式。
- 你可以使用裝飾器輕鬆地監控 Python 函式的 CPU 與記憶體使用情況。
🔗 參考資料