使用python定时采样linux cpu占用率

# -*- coding: utf-8 -*-

import threading, time

class GetCpuInfo(threading.Thread):
    def __init__(self, interval_time):
        threading.Thread.__init__(self)
        self.alive = True
        self.cpuinfo_list = []
        self._interval_time = interval_time

    def get_cpu_useage(self):
        '''读取stat,计算用户cpu占用率'''
        _cpu_info = {}
        with open("/proc/stat") as f:
            lines = f.readlines()

        for line in lines:
            if line.strip() == "":
                continue
            cpu_values = line.split(' ')
            values = [i for i in cpu_values if i.strip() != ""]
            if values[0].strip() != "cpu":
                continue
            # totalCpuTime = user + nice + system + idle + iowait + irq +
            # softirq + stealstolen  +  guest
            # values中余下9个对应上述值
            _cpu_info["totalCpuTime"] = 0
            for i in range(1, 9):
                _cpu_info["totalCpuTime"] += int(values[i].strip())

            _cpu_info["userCpuTime"] = 0
            for i in range(1, 3):
                _cpu_info["userCpuTime"] += int(values[i].strip())
            break
        return _cpu_info

    def run(self):
        while self.alive:
            time.sleep(self._interval_time)
            cpu_info = self.get_cpu_useage()
            # 计算cpu占用率
            if cpu_info != {}:
                cpu_usage = cpu_info["userCpuTime"] * 100 / cpu_info["totalCpuTime"]
                self.cpuinfo_list.append(cpu_usage)

    def stop_task(self):
        self.alive = False

    def get_cpuinfo(self):
        return self.cpuinfo_list

if __name__ == "__main__":
    # 每2秒采样一次
    cpu = GetCpuInfo(2)
    cpu.start()
    time.sleep(10)
    cpu.stop_task()
    print cpu.get_cpuinfo()

你可能感兴趣的:(使用python定时采样linux cpu占用率)