Get per CPU usage

Source: Internet
Author: User

The following is a script for using Python to get the server per CPU usage.

#!/usr/bin/env python#-*-coding:utf-8-*-ImportRe,timedef_read_cpu_usage ():"""Read The current system CPU usage From/proc/stat"""Statfile="/proc/stat"cpulist= []         Try: F= Open (Statfile,'R') Lines=F.readlines ()except:                 Print "Error:can not open%s,the system cannot continue to run"%(Statfile)return []          forLineinchlines:tmplist=Line.split ()ifLen (tmplist) < 5:                Continue             forBinchtmplist:m= Re.search (r'cpu\d+', B)ifM is  notNone:cpulist.append (tmplist) f.close ()returncpulistdefget_cpu_usage (): CPUUsage={} Cpustart={} cpuend={} Linestart=_read_cpu_usage ()if  notLinestart:return0 forCpustrinchLinestart:usni=long (Cpustr[1]) +long (cpustr[2]) +long (cpustr[3]) +long (cpustr[5]) +long (cpustr[6]) +long (cpustr[7]) +long (cpustr[4]) USN=long (Cpustr[1]) +long (cpustr[2]) +long (cpustr[3]) cpustart[cpustr[0]]= str (USNI) +":"+STR (USN) Sleep= 2time.sleep (sleep) lineend=_read_cpu_usage ()if  notLineend:return0 forCpustrinchLineend:usni=long (Cpustr[1]) +long (cpustr[2]) +long (cpustr[3]) +long (cpustr[5]) +long (cpustr[6]) +long (cpustr[7]) +long (cpustr[4]) USN=long (Cpustr[1]) +long (cpustr[2]) +long (cpustr[3]) cpuend[cpustr[0]]= str (USNI) +":"+Str (USN) forLineinchCpustart:start= Cpustart[line].split (':') USNI1,USN1= Float (start[0]), float (start[1]) End= Cpuend[line].split (':') USNI2,USN2= Float (end[0]), float (end[1]) Cpuper= (USN2-USN1)/(usni2-usni1) Cpuusage[line]= Int (100*cpuper)returnCPUUsageif __name__=='__main__': A=get_cpu_usage ()PrintA

Get per CPU usage

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.