在计算机系统管理和应用性能优化中,监控进程的CPU、内存和IO使用率是非常重要的任务。Python作为一种功能强大的编程语言,可以轻松地实现这些监控任务。勇哥将介绍如何使用Python写一个简单使用的监控进程的CPU、内存和IO使用率的工具。
准备工作
啥也不说,先装库:psutil是一个跨平台用于获取系统信息(包括进程信息)的流行库;安装命令:
pip install psutil
监控CPU使用率
使用psutil库可以轻松地监控进程的CPU使用率。以下是一个示例代码,演示了如何监控一个指定进程的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() # 替换为你要监控的进程ID
monitoring_duration = 60 # 监控持续时间(秒)
monitor_cpu(target_process_id, monitoring_duration)
通过cpu_percent() 获取进程的CPU使用率,然后调整interval参数,控制采样时间间隔,再加个循环,就实现了不停获取数据信息的小脚本,自己可以扩展将结果写入文件或者数据库种用来持久化输出了。
监控内存使用率
psutil库的memory_info()方法可以获取进程的内存占用,废话不多说上代码:
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"内存使用量: {memory_info.rss / (1024 * 1024):.2f} MB")
print(f"内存使用率: {memory_percent:.2f}%")
time.sleep(1)
if __name__ == "__main__":
target_process_id = os.getpid() # 替换为你要监控的进程ID
monitoring_duration = 60 # 监控持续时间(秒)
其中rss属性可以获取实际使用物理内存,memory_info() 获取进程的内存信息,简短的代码就实现了内存监控,可以自己适当扩展了。
监控IO使用率
psutil库的io_counters()方法可以监控进程的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"读取字节数: {io_counters.read_bytes}") # 要变成MB,需要除1024/1024
print(f"写入字节数: {io_counters.write_bytes}")
time.sleep(1)
if __name__ == "__main__":
target_process_id = os.getpid() # 替换为你要监控的进程ID
monitoring_duration = 60 # 监控持续时间(秒)
monitor_io(target_process_id, monitoring_duration)
io_counters()方法返回了进程的IO计数器信息,可以读取和写入的字节数。
小工具代码整合
上面3个小函数已经实现了监控我门常规的信息了,现在我们的要求是要同时监控,而不是监控完这个再监控那个,对吧。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"读取字节数: {io_counters.read_bytes / 1024 / 1024} MB")
print(f"写入字节数: {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"内存使用量: {memory_info.rss / (1024 * 1024):.2f} MB")
print(f"内存使用率: {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("请输入进程ID:"))
duration = int(input("请输入监控时长(秒):"))
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())