This article describes how to obtain the CPU usage trend chart of a single program using Python. in this article, matplotlib is used to visualize the data. if you need it, refer to the position in this article: you have saved the CPU history data disk, wait for the visualization to perform analysis.
The previous article (http://www.jb51.net/article/61956.htm) mentioned how to use python to store the results of the top command in linux, this article is its follow-up.
In python, we can use matplotlib to conveniently visualize data, for example, the following code:
The code is as follows:
Import matplotlib. pyplot as plt
List1 = [1, 2, 3]
List2 = [4, 5, 9]
Plt. plot (list1, list2)
Plt. show ()
The execution result is as follows:
The above is just to pass two list data structures to the plot function, show will come out ...... Haha, it's very convenient!
This is used to obtain the CPU trend chart!
But the data we get is not that friendly now. for example, if I have a file (file.txt), the content is as follows:
The code is as follows:
Cpu (s): 0.0% us, 0.0% sy, 0.0% ni, 100.0% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
Cpu (s): 7.7% us, 7.7% sy, 0.0% ni, 76.9% id, 0.0% wa, 0.0% hi, 7.7% si, 0.0% st
Cpu (s): 0.0% us, 9.1% sy, 0.0% ni, 90.9% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
Cpu (s): 9.1% us, 0.0% sy, 0.0% ni, 90.9% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
Cpu (s): 8.3% us, 8.3% sy, 0.0% ni, 83.3% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
Cpu (s): 0.0% us, 0.0% sy, 0.0% ni, 100.0% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
Cpu (s): 0.0% us, 9.1% sy, 0.0% ni, 90.9% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
Cpu (s): 0.0% us, 0.0% sy, 0.0% ni, 100.0% id, 0.0% wa, 0.0% hi, 0.0% si, 0.0% st
The first column is the time column, and the sixth column is the idle value of the CPU.
We have to do some work to figure out the CPU usage trend from this set of data.
The following is the code. here is an idea. you need to copy it back and modify it:
The code is as follows:
# Coding: UTF-8
'''
File: cpuUsage. py
Author: Mike
E-mail: Mike_Zhang@live.com
'''
Import matplotlib. pyplot as plt
Import string
Def getCpuInfData (fileName ):
Ret = {}
F = open (fileName, "r ")
LineList = f. readlines ()
For line in lineList:
Tmp = line. split ()
Sz = len (tmp)
T_key = string. atoi (tmp [0]) # obtain the key
T_value = 100.001-string. atof (line. split (':') [1]. split (',') [3]. split ('%') [0]) # get value
Print t_key, t_value
If not ret. has_key (t_key ):
Ret [t_key] = []
Ret [t_key]. append (t_value)
F. close ()
Return ret
RetMap1 = getCpuInfData ("file.txt ")
# Generate a CPU usage trend chart
List1 = retMap1.keys ()
List1.sort ()
List2 = []
For I in list1: list2.append (retMap1 [I])
Plt. plot (list1, list2)
Plt. show ()
Okay, that's all. I hope it will help you.