总体思路
- 使用python脚本周期性获取CPU和内存的使用率,并记录到csv文件中
- 利用Excel/WPS表格的折线图汇出结果
运行Python脚本
- 需要使用psutil这个包,可以直接安装python-psutil或者通过pip install psutil
- 先给出参考代码
$ cat resource_record.py
#!/usr/bin/python
import psutil
import os,datetime,time
record_interval = 0.5 # unit is second
def getMemCpu():
data = psutil.virtual_memory()
total = data.total
free = data.available
memory = str(int(round(data.percent)))+"%"
cpu = str(psutil.cpu_percent(interval=record_interval ))+"%"
return (cpu,memory)
def main():
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
fname = now+r"-report.csv"
with open('%s' % fname,'w') as f:
title_str = "Time, CPU ,Mem"
print title_str
f.write("Time, CPU ,Mem"+"\n")
for i in xrange(999999):
info = getMemCpu()
tmp_str = "%4s,%5s,%4s" % (i*record_interval,info[0],info[1])
print tmp_str
f.write(tmp_str+"\n")
if __name__=="__main__":
main()
~
- 运行一段时间后ctrl+c强行中断
$ python resource_record.py
Time, CPU ,Mem
0.0, 1.7%, 18%
0.5, 0.8%, 18%
1.0, 1.6%, 18%
1.5, 1.3%, 18%
2.0,25.4%, 18%
2.5,23.7%, 18%
3.0,25.2%, 18%
3.5,23.8%, 18%
4.0,24.3%, 18%
4.5,23.3%, 18%
5.0,25.3%, 18%
...
^CTraceback (most recent call last):
File "resource_record.py", line 29, in <module>
main()
File "resource_record.py", line 23, in main
time.sleep(record_interval)
KeyboardInterrupt
- 当前目录下多了按照日期时间命名的csv文件
$ cat 2020-04-30-11_09_22-report.csv
Time, CPU ,Mem
0.0, 1.7%, 18%
0.5, 0.8%, 18%
1.0, 1.6%, 18%
1.5, 1.3%, 18%
...
绘图
-
将csv文件导出,用Excel或WPS打开
-
选择插入折线图
-
在图上右击,点“选择数据”,将Time前面的对勾去掉,点“确定”
-
此时横轴还需要调整,“选择数据”->修改“类别”,选择第一列的数值
-
可以看出效果了,后面就自己美化吧
-
当前的csv文件是无法保存折线图的,需要另存为xls或xlsx文件
网友评论