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.