最近,在做项目的时候,需要监控cpu以及内存的使用情况,做了一个比较简单的脚本,非常适合刚入门python的新手同学。
(关注“测试开发自动化” 弓中皓,获取更多学习内容)
一、代码说明:
1.代码用到了psutil第三方库(需要提前导入);
2.代码主要分为监控功能和写入日志两部分,运行代码后,在路径下可以生成一个.log文件,记录监控信息;
3.使用时只需要将代码中 if pid.pid == 31928 后面的数字修改为要监控的pid即可。
注:这个pid我们可以通过任务管理器来进行查看:
二、python代码如下所示:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import psutil
class MonitorCPUMemory():
def __init__(self):
pass
def write(self, text1, text2, text3):
"""写入log中"""
timer = time.strftime("%Y-%m-%d %H:%M:%S")
with open('text.log', 'a+', encoding='utf-8') as tf:
text = timer + " 内存占用率= {}% ,软件cpu使用率为 {}%,系统cpu使用率为 {}%\n".format(text1, text2, text3)
tf.write(text)
def CM_monitor(self):
"""CPU+内存监控"""
for i in psutil.pids():
pid = psutil.Process(i)
if pid.pid == 31928: # 这里修改索要监控的pid
while True:
a = pid.memory_percent() # 内存占用%
b = pid.cpu_percent()
c = psutil.cpu_percent()
time.sleep(1)
self.write(a, b, c)
if __name__ == '__main__':
a = MonitorCPUMemory()
a.CM_monitor()
text.log文件中监控信息:
2022-04-15 17:20:01 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 14.0%
2022-04-15 17:20:02 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.5%
2022-04-15 17:20:03 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.5%
2022-04-15 17:20:04 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.9%
2022-04-15 17:20:05 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.8%
2022-04-15 17:20:06 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.3%
2022-04-15 17:20:07 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 1.0%
2022-04-15 17:20:08 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.9%
2022-04-15 17:20:09 内存占用率= 11.355243691095298% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.8%
2022-04-15 17:20:10 内存占用率= 11.355243691095298% ,软件cpu使用率为 17.2%,系统cpu使用率为 1.9%
2022-04-15 17:20:11 内存占用率= 11.355243691095298% ,软件cpu使用率为 26.2%,系统cpu使用率为 3.9%
2022-04-15 17:20:12 内存占用率= 11.355267837933186% ,软件cpu使用率为 40.6%,系统cpu使用率为 5.6%
2022-04-15 17:20:13 内存占用率= 11.355364425284733% ,软件cpu使用率为 7.7%,系统cpu使用率为 1.5%
2022-04-15 17:20:19 内存占用率= 11.3572961723157% ,软件cpu使用率为 0.0%,系统cpu使用率为 8.8%
2022-04-15 17:20:20 内存占用率= 11.35719958496415% ,软件cpu使用率为 12.3%,系统cpu使用率为 2.9%
2022-04-15 17:20:21 内存占用率= 11.358406926858503% ,软件cpu使用率为 9.4%,系统cpu使用率为 2.6%
2022-04-15 17:20:22 内存占用率= 11.358672542075261% ,软件cpu使用率为 20.3%,系统cpu使用率为 5.7%
2022-04-15 17:20:23 内存占用率= 11.35802057745231% ,软件cpu使用率为 4.6%,系统cpu使用率为 3.2%
2022-04-15 17:20:24 内存占用率= 11.357706668559779% ,软件cpu使用率为 0.0%,系统cpu使用率为 1.3%
2022-04-15 17:20:25 内存占用率= 11.357706668559779% ,软件cpu使用率为 0.0%,系统cpu使用率为 0.7%
2022-04-15 17:20:26 内存占用率= 11.357730815397666% ,软件cpu使用率为 0.0%,系统cpu使用率为 1.0%
2022-04-15 17:20:27 内存占用率= 11.357392759667247% ,软件cpu使用率为 0.0%,系统cpu使用率为 1.9%
(关注“测试开发自动化” 弓中皓,获取更多学习内容)