Python测试进阶——(4)Python程序监控、存储、分析并可视化CPU和内存利用率

monitor190617.py 监控cpu和内存利用率信息,组织成json格式,并写入到 record.txt 文件中:

import psutil
import time
import json

a = {}
flag=1
f = open('record.txt', 'a')
f.truncate()
    
while flag < 10:
    b = {}
    b['cpu'] = psutil.cpu_percent(1)
    b['memory'] = psutil.virtual_memory().percent
    a[time.strftime("%H:%M:%S", time.localtime())] = b.copy()
    #print(a)
    #print(json.dumps(a))
    flag += 1
    time.sleep(4)
    
#json.dump(a,f)
f.write(json.dumps(a))
f.close()

record.txt 的文件内容为:

{
     "11:39:57": {
     "cpu": 12.5, "memory": 49.7}, "11:40:02": {
     "cpu": 18.6, "memory": 49.6}, "11:40:07": {
     "cpu": 11.8, "memory": 49.5}, "11:40:12": {
     "cpu": 10.7, "memory": 49.5}, "11:40:17": {
     "cpu": 12.4, "memory": 49.3}, "11:40:22": {
     "cpu": 12.9, "memory": 49.2}, "11:40:27": {
     "cpu": 6.1, "memory": 49.0}, "11:40:32": {
     "cpu": 19.4, "memory": 48.7}, "11:40:37": {
     "cpu": 16.9, "memory": 49.3}}

编写 show190617.py ,读取 record.txt 的文件内容,做统计分析,并将分析结果可视化为图表:

import json
import pandas as pd
import matplotlib.pyplot as plt
    
with open('record.txt','rb') as f:
    a = json.loads(f.read())
    #print('load 并赋值给a后的数据类型:',type(a))
    #print(a)
    
#print(a)

#print('*' * 50)

time = []
cpu = []
mem = []

for key in a.items():
    #print(key)
    #print('key的数据类型:',type(key))
    time.append(key[0])
    #print(key[1])
    #print('key[1]的数据类型:',type(key[1]))
    cpu.append(key[1]['cpu'])
    mem.append(key[1]['memory'])
    
print(time)
print(cpu)
print(mem)

s_cpu = pd.Series(cpu)
s_mem = pd.Series(mem)
cpu_mean = s_cpu.mean()
mem_mean = s_mem.mean()
print('cpu利用率平均值是:%f' % cpu_mean)
print('内存利用率平均值是:%f' % mem_mean)

plt.plot(time,cpu, c='r')
plt.plot(time,mem, c='b')
plt.show()

返回信息:

['11:39:57', '11:40:02', '11:40:07', '11:40:12', '11:40:17', '11:40:22', '11:40:27', '11:40:32', '11:40:37']
[12.5, 18.6, 11.8, 10.7, 12.4, 12.9, 6.1, 19.4, 16.9]
[49.7, 49.6, 49.5, 49.5, 49.3, 49.2, 49.0, 48.7, 49.3]
cpu利用率平均值是:13.477778
内存利用率平均值是:49.311111

并显示图表:

Python测试进阶——(4)Python程序监控、存储、分析并可视化CPU和内存利用率_第1张图片

 

参考:

https://www.cnblogs.com/luotianshuai/p/5002110.html

https://www.runoob.com/python/python-dictionary.html

https://www.runoob.com/python/python-tuples.html

https://www.cnblogs.com/onemorepoint/p/7482644.html

https://blog.csdn.net/lambsnow/article/details/78517340

https://www.cnblogs.com/haiyan123/p/8377636.html

https://www.cnblogs.com/fat39/p/7159881.html

转载于:https://www.cnblogs.com/ratels/p/11037661.html

你可能感兴趣的:(python,json)