本文定位:已將CPU歷史數(shù)據(jù)存盤,等待可視化進(jìn)行分析,可暫時沒有思路。
前面一篇文章(//m.survivalescaperooms.com/article/61956.htm)提到過在linux下如何用python將top命令的結(jié)果進(jìn)行存盤,本文是它的后續(xù)。
python中我們可以用matplotlib很方便的將數(shù)據(jù)可視化,比如下面的代碼:
list1 = [1,2,3]
list2 = [4,5,9]
plt.plot(list1,list2)
plt.show()
執(zhí)行效果如下:

上面只是給plot函數(shù)傳了兩個list數(shù)據(jù)結(jié)構(gòu),show一下圖形就出來了……哈哈,很方便吧!
獲取CPU趨勢圖就用這個了!
可我們現(xiàn)在得到的數(shù)據(jù)沒那么友好,比如我現(xiàn)在有個文件(file.txt),內(nèi)容如下:
其中,第一列為時間,第六列為CPU的idle值。
要從這組數(shù)據(jù)中得出CPU使用情況趨勢圖,我們就要做些工作了。
下面是代碼,這里提供一個思路,需要的朋友拷回去改一下吧:
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]) # 得到key
t_value = 100.001-string.atof(line.split(':')[1].split(',')[3].split('%')[0]) # 得到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")
# 生成CPU使用情況趨勢圖
list1 = retMap1.keys()
list1.sort()
list2 = []
for i in list1:list2.append(retMap1[i])
plt.plot(list1,list2)
plt.show()
好,就這些了,希望對你有幫助。
新聞熱點(diǎn)
疑難解答
圖片精選