Use python to calculate the CPU and Memory usage of a process in the top Command

Source: Internet
Author: User
In performance tests, top commands are often used to monitor the CPU and memory usage of a process over a period of time. Output to the file once every 10 seconds. The following code processes the output top file and obtains the CPU utilization. memory has the largest, minimum, and average value. Topfile = raw_input ("please input the topfile path :")
Try:
Top = open (topfile, "r ")
Handle t IOError:
Print "No such file, please check your input"
Cpulist = []
Memorylist = [] print "#" * 50
Print "1. if you want to get the max cpu and memory, please input toptest. getMaxValue () \ n"
Print "2. if you want to get the min cpu and memory, please input toptest. getMinValue () \ n"
Print "3. if you want to get the average cpu and memory, please input toptest. getAvgValue () \ n"
Print "#" * 50 # get the max value of CPU and memory

Def getMaxValue ():
CpuPid = int (raw_input ("please input the pid :"))
# Print cpuPid
LineList = top. readlines ()
Length = len (lineList)
For I in range (0, length ):
Try:
Pid = int (lineList [I] [: 6])
# Print "pid =" + str (pid), "cpuPid =" + str (cpuPid)
If pid = cpuPid:
# Print "#" * 10
# Print float (lineList [I] [55: 60])
Cpulist. append (float (lineList [I] [55: 60])
Memorylist. append (float (lineList [I] [29:33])
Else:
"It is not a pid line"
Failed t ValueError:
"Print the valueError"
Print "the max CPU use is:" + str (max (cpulist) + "%"
Print "the max Memory use is:" + str (max (Memorylist ))

# Get the mim value of CPU and memorydef getMinValue ():
Print "the min CPU use is:" + str (min (cpulist) + "%"
Print "the max Memory use is:" + str (min (Memorylist) def getAvgValue ():
Print "the average CPU use is:" + str (float (sum (cpulist)/len (cpulist) + "%"
Print "the average Memory use is:" + str (float (sum (Memorylist)/len (Memorylist ))
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.