实现统计 android手机 CPU使用率

 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            
原文地址:https://www.cnblogs.com/aziji/p/9628327.html