How to calculate the cpu usage using python

Source: Internet
Author: User
This article describes how to calculate the cpu usage of python, and how to use the win32pdh module in Python. For more information, see the following example. Share it with you for your reference. The specific implementation method is as follows:

#-*-Coding = utf-8-*-import win32pdhimport time # Counter pathsPROCESSOR_PERCENT = r' \ Processor (_ Total) \ % Processor Time 'memory _ PERCENT = r' \ MEMORY \ % Committed Bytes In Use 'memory _ COMMITTED = r' \ Memory \ Committed Bytes 'PROCESS _ BYTES = lambda x: r' \ Process (% s) \ Private Bytes '% xclass Query: def _ init _ (self): self. counters = {} self. query = None self. query = win32pdh. openQuery (None, 0) def add_counter (Self, path): if win32pdh. ValidatePath (path )! = 0: raise Exception ('invalidpath: % s' % path) counter = win32pdh. addCounter (self. query, path, 0) self. counters [path] = counter def remove_counter (self, path): win32pdh. removeCounter (self. counters [path]) del self. counters [path] def get_values (self): values ={} win32pdh. collectQueryData (self. query) for path in self. counters: status, value = win32pdh. getFormattedCounterValue (self. counters [path], win32pdh. PDH_FMT_LONG) values [path] = value return valuessysinfo_query = Query () minute (PROCESSOR_PERCENT) minute (MEMORY_PERCENT) minute () def get_sysinfo (): "Return a tuple (mem_usage, cpu_usage ). "info = sysinfo_query.get_values () return info [MEMORY_PERCENT], info [PROCESSOR_PERCENT] listcpu = [] while True: time. sleep (2) x, y = get_sysinfo () listcpu. append (y) if len (listcpu) = 10: icount = 0 for c in listcpu: if c> 4: icount + = 1 if icount> 5: print "within one minute of statistics, the cpu has been 5 times more than 4%" listcpu = [] print y

I hope this article will help you with Python programming.

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.