python統計cpu利用率的方法

來源:互聯網
上載者:User
本文執行個體講述了python統計cpu利用率的方法。分享給大家供大家參考。具體實現方法如下:

#-*-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('Invalid path: %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()sysinfo_query.add_counter(PROCESSOR_PERCENT)sysinfo_query.add_counter(MEMORY_PERCENT)sysinfo_query.get_values()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 "在統計的1分鐘內,cpu已經有5次大於4%"    listcpu=[]  print y

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.