在計算機系統(tǒng)管理和應(yīng)用性能優(yōu)化中,監(jiān)控進(jìn)程的CPU、內(nèi)存和IO使用率是非常重要的任務(wù)。Python/ target=_blank class=infotextkey>Python作為一種功能強大的編程語言,可以輕松地實現(xiàn)這些監(jiān)控任務(wù)。勇哥將介紹如何使用Python寫一個簡單使用的監(jiān)控進(jìn)程的CPU、內(nèi)存和IO使用率的工具。
準(zhǔn)備工作
啥也不說,先裝庫:psutil是一個跨平臺用于獲取系統(tǒng)信息(包括進(jìn)程信息)的流行庫;安裝命令:
pip install psutil
監(jiān)控CPU使用率
使用psutil庫可以輕松地監(jiān)控進(jìn)程的CPU使用率。以下是一個示例代碼,演示了如何監(jiān)控一個指定進(jìn)程的CPU使用率:
import psutil
import os
import time
def monitor_cpu(process_id, duration):
process = psutil.Process(process_id)
start_time = time.time()
while time.time() - start_time < duration:
cpu_percent = process.cpu_percent(interval=1)
print(f"CPU 使用率: {cpu_percent}%")
if __name__ == "__mAIn__":
target_process_id = os.getpid() # 替換為你要監(jiān)控的進(jìn)程ID
monitoring_duration = 60 # 監(jiān)控持續(xù)時間(秒)
monitor_cpu(target_process_id, monitoring_duration)
通過cpu_percent() 獲取進(jìn)程的CPU使用率,然后調(diào)整interval參數(shù),控制采樣時間間隔,再加個循環(huán),就實現(xiàn)了不停獲取數(shù)據(jù)信息的小腳本,自己可以擴展將結(jié)果寫入文件或者數(shù)據(jù)庫種用來持久化輸出了。
監(jiān)控內(nèi)存使用率
psutil庫的memory_info()方法可以獲取進(jìn)程的內(nèi)存占用,廢話不多說上代碼:
import psutil
import os
import time
def monitor_memory(process_id, duration):
process = psutil.Process(process_id)
start_time = time.time()
while time.time() - start_time < duration:
memory_info = process.memory_info()
memory_percent = process.memory_percent()
print(f"內(nèi)存使用量: {memory_info.rss / (1024 * 1024):.2f} MB")
print(f"內(nèi)存使用率: {memory_percent:.2f}%")
time.sleep(1)
if __name__ == "__main__":
target_process_id = os.getpid() # 替換為你要監(jiān)控的進(jìn)程ID
monitoring_duration = 60 # 監(jiān)控持續(xù)時間(秒)
其中rss屬性可以獲取實際使用物理內(nèi)存,memory_info() 獲取進(jìn)程的內(nèi)存信息,簡短的代碼就實現(xiàn)了內(nèi)存監(jiān)控,可以自己適當(dāng)擴展了。
監(jiān)控IO使用率
psutil庫的io_counters()方法可以監(jiān)控進(jìn)程的IO操作,廢話不多說,上代碼:
import psutil
import os
import time
def monitor_io(process_id, duration):
process = psutil.Process(process_id)
start_time = time.time()
while time.time() - start_time < duration:
io_counters = process.io_counters()
print(f"讀取字節(jié)數(shù): {io_counters.read_bytes}") # 要變成MB,需要除1024/1024
print(f"寫入字節(jié)數(shù): {io_counters.write_bytes}")
time.sleep(1)
if __name__ == "__main__":
target_process_id = os.getpid() # 替換為你要監(jiān)控的進(jìn)程ID
monitoring_duration = 60 # 監(jiān)控持續(xù)時間(秒)
monitor_io(target_process_id, monitoring_duration)
io_counters()方法返回了進(jìn)程的IO計數(shù)器信息,可以讀取和寫入的字節(jié)數(shù)。
小工具代碼整合 上面3個小函數(shù)已經(jīng)實現(xiàn)了監(jiān)控我門常規(guī)的信息了,現(xiàn)在我們的要求是要同時監(jiān)控,而不是監(jiān)控完這個再監(jiān)控那個,對吧。so 勇哥使用異步編程來簡單帶大伙玩一下,完整代碼如下:
import asyncio
import time
import psutil
async def monitor_io(process_id, duration):
process = psutil.Process(process_id)
start_time = time.time()
while time.time() - start_time < duration:
io_counters = process.io_counters()
print(f"讀取字節(jié)數(shù): {io_counters.read_bytes / 1024 / 1024} MB")
print(f"寫入字節(jié)數(shù): {io_counters.write_bytes / 1024 / 1024} MB")
await asyncio.sleep(1)
async def monitor_memory(process_id, duration):
process = psutil.Process(process_id)
start_time = time.time()
while time.time() - start_time < duration:
memory_info = process.memory_info()
memory_percent = process.memory_percent()
print(f"內(nèi)存使用量: {memory_info.rss / (1024 * 1024):.2f} MB")
print(f"內(nèi)存使用率: {memory_percent:.2f}%")
await asyncio.sleep(1)
async def monitor_cpu(process_id, duration):
process = psutil.Process(process_id)
start_time = time.time()
while time.time() - start_time < duration:
cpu_percent = process.cpu_percent(interval=1)
print(f"CPU 使用率: {cpu_percent}%")
await asyncio.sleep(1)
async def main():
process_id = int(input("請輸入進(jìn)程ID:"))
duration = int(input("請輸入監(jiān)控時長(秒):"))
tasks = [
monitor_io(process_id, duration),
monitor_memory(process_id, duration),
monitor_cpu(process_id, duration)
]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())