python实现监控指定进程的cpu和内存使用率
作者:踏莎行hyx 时间:2023-08-23 02:21:17
为了测试某个服务的稳定性,通常需要在服务长时间运行的情况下,监控其资源消耗情况,比如cpu和内存使用
这里借助python的psutil这个包可以很方便的监控指定进程号(PID)的cpu和内存使用情况
代码
process_monitor.py
import sys
import time
import psutil
# get pid from args
if len(sys.argv) < 2:
print ("missing pid arg")
sys.exit()
# get process
pid = int(sys.argv[1])
p = psutil.Process(pid)
# monitor process and write data to file
interval = 3 # polling seconds
with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f:
f.write("time,cpu%,mem%\n") # titles
while True:
current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
cpu_percent = p.cpu_percent() # better set interval second to calculate like: p.cpu_percent(interval=0.5)
mem_percent = p.memory_percent()
line = current_time + ',' + str(cpu_percent) + ',' + str(mem_percent)
print (line)
f.write(line + "\n")
time.sleep(interval)
支持跨平台linux,windows,mac
根据pid号获取进程实例,固定时间间隔查询其cpu和内存的使用百分比
将监控数据写入文件,一边后续分析
必要的话,也可以额外统计整个机器的资源状况
实例
使用命令
python process_monitor.py 25272
文件保存结果
绘制出曲线图
来源:https://blog.csdn.net/u012234115/article/details/102687721
标签:python,进程,内存
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
IE6图片加载的一个BUG解决方法
2023-09-16 03:20:10
Mysql InnoDB的锁定机制实例详解
2024-01-23 17:32:27
Python中的四种交换数值的方法解析
2021-07-01 12:42:02
![](https://img.aspxhome.com/file/2023/6/131086_0s.png)
使用Python读取大文件的方法
2022-02-18 00:43:35
Python中使用asyncio 封装文件读写
2022-11-13 03:18:12
HTML5 Canvas 起步(3) - 颜色与渐变
2009-06-08 12:58:00
![](https://img.aspxhome.com/file/UploadPic/20096/8/3-colors-72s.jpg)
Insert into与AddNew哪一个更好?
2009-10-28 18:30:00
一个修改Oracle数据库用户密码的小诀窍
2009-09-30 15:29:00
用python给csv里的数据排序的具体代码
2021-02-15 01:12:25
Pyecharts 中Geo函数常用参数的用法说明
2022-06-07 08:35:06
![](https://img.aspxhome.com/file/2023/5/65075_0s.jpg)
深入SQL Server中char、varchar、text和nchar、nvarchar、ntext的区别详解
2024-01-26 11:26:57
Python Web框架Flask中使用七牛云存储实例
2022-11-25 17:20:27
Go GORM 事务详细介绍
2024-02-21 21:03:05
SQLserver中字符串查找功能patindex和charindex的区别
2012-06-06 20:20:42
JS实现页面滚动到关闭时的位置与不滚动效果
2024-04-10 10:47:56
如何创建第一个Pygame程序
2022-12-05 21:02:12
![](https://img.aspxhome.com/file/2023/7/79617_0s.gif)
python pyppeteer 破解京东滑块功能的代码
2022-10-24 06:04:10
SQL 统计一个数据库中所有表记录的数量
2012-01-29 18:21:36
Java实现上传Excel文件并导入数据库
2024-01-22 02:47:44
javascript 自动转到命名锚记
2024-04-29 13:44:46