这篇文章给大家介绍python是怎样实现监控指定进程的cpu和内存使用率,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
为了测试某个服务的稳定性,通常需要在服务长时间运行的情况下,监控其资源消耗情况,比如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
文件保存结果
绘制出曲线图
关于python是怎样实现监控指定进程的cpu和内存使用率就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。