实现统计 android手机 CPU使用率

2018-09-18 06:42:14来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 1 # -*- coding:utf-8 -*-
 2 '''
 3 Created on Sep 10, 2018
 4 
 5 @author: SaShuangYiBing
 6 '''
 7 import subprocess
 8 import time
 9 
10 class CPU_usage(object):
11     """
12     CPU统计方法是参照:https://blog.csdn.net/xiaodanpeng/article/details/53503076
13     
14     """
15     def __init__(self,t0):
16         self.time = t0
17     
18     def read_cpu(self):
19         cpu_info0 = []
20         cpu_info1 = subprocess.check_output('adb shell cat /proc/stat').decode().split()[1:11]
21         for i in cpu_info1:
22             cpu_info0.append(int(i))
23         return cpu_info0
24     
25     def get_idle(self):
26         cpu_idle = self.read_cpu()[3]
27         return cpu_idle
28     
29     def cal_cpu(self):
30         t1_total = sum(self.read_cpu())
31         t1_idle = self.get_idle()
32         time.sleep(self.time)
33         t2_total = sum(self.read_cpu())
34         t2_idle = self.get_idle()
35         cpu_usage = (1 - (t2_idle - t1_idle)/(t2_total - t1_total))*100
36         if cpu_usage < 0:
37             return cpu_usage == 0
38         else:
39             return cpu_usage
40 
41 if __name__ == "__main__":
42        cal_cpu = CPU_usage(1)
43        while True:
44            print (time.strftime('%Y-%m-%d %H:%M:%S') + " The CPU usage is %d" %cal_cpu.cal_cpu() + "%")
45            

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python操作mongodb方法(附源码)!

下一篇:Python3 urllib 与 Python2 urllib的变化