Python性能测试服务器进程资源消耗

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)