本文定位:已将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()
好,就这些了,希望对你有帮助。

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
