import psutil
import time
def monitor_process(pid, duration):
process = psutil.Process(pid)
cpu_percent_history = []
memory_percent_history = []
disk_io_history = []
network_io_history = []
start_time = time.time()
while time.time() - start_time < duration:
cpu_percent_history.append(process.cpu_percent())
memory_percent_history.append(process.memory_percent())
disk_io_history.append(process.io_counters().read_bytes + process.io_counters().write_bytes)
network_io_history.append(psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv)
time.sleep(1)
average_cpu_percent = sum(cpu_percent_history) / len(cpu_percent_history)
average_memory_percent = sum(memory_percent_history) / len(memory_percent_history)
total_disk_io = disk_io_history[-1] - disk_io_history[0]
total_network_io = network_io_history[-1] - network_io_history[0]
return {
'average_cpu_percent': average_cpu_percent,
'average_memory_percent': average_memory_percent,
'total_disk_io': total_disk_io,
'total_network_io': total_network_io
}
pid = 1234 # 替换为你要测试的进程的PID
duration = 60 # 测试时长,单位是秒
result = monitor_process(pid, duration)
print(result)
本文介绍了一个使用Python的psutil库实现的函数,用于监控指定进程在给定时间内的CPU使用率、内存占用、磁盘读写和网络流量。
8518

被折叠的 条评论
为什么被折叠?



