Python擷取單個程式CPU使用方式趨勢圖

來源:互聯網
上載者:User
本文定位:已將CPU曆史資料存檔,等待可視化進行分析,可暫時沒有思路。
前面一篇文章(http://www.jb51.net/article/61956.htm)提到過在linux下如何用python將top命令的結果進行存檔,本文是它的後續。

python中我們可以用matplotlib很方便的將資料視覺效果,比如下面的代碼:
複製代碼 代碼如下:


import matplotlib.pyplot as plt

list1 = [1,2,3]
list2 = [4,5,9]
plt.plot(list1,list2)
plt.show()

執行效果如下:

上面只是給plot函數傳了兩個list資料結構,show一形就出來了……哈哈,很方便吧!
擷取CPU趨勢圖就用這個了!
可我們現在得到的資料沒那麼友好,比如我現在有個檔案(file.txt),內容如下:

複製代碼 代碼如下:


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

其中,第一列為時間,第六列為CPU的idle值。

要從這組資料中得出CPU使用方式趨勢圖,我們就要做些工作了。

下面是代碼,這裡提供一個思路,需要的朋友拷回去改一下吧:
複製代碼 代碼如下:


#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]) # 得到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()

好,就這些了,希望對你有協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.