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

本文介绍了一个使用Python的psutil库实现的函数,用于监控指定进程在给定时间内的CPU使用率、内存占用、磁盘读写和网络流量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值