#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import time
import csv
from datetime import datetime
class Controller(object):
# 获取当前时间:年月日时分秒毫秒
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-4]
# 单次操作,获取cpu运行时的信息
def testprocess(self):
# 获取包名 这一步放到后面再优化,自动获取当前运行的app的pagename
# pagename = os.popen("adb shell dumpsys window | findstr mCurrentFocus")
# 执行固定命令,获取trip的cpu信息,这个是b站的命令,但这个命令显示的是 进程累计占用 CPU 的时间
# (如 3% TOTAL 表示进程在统计周期内占用了 3% 的 CPU 时间),而非实时使用率
# result = os.popen("adb shell dumpsys cpuinfo | findstr ctrip.english")
# 所以这里换这个命令
result = os.popen("adb shell top -n 1 | findstr ctrip.english").read()
# print(result)
# 输出的结果:23461 u0_a285 16 -4 65G 797M 450M S 130 10.6 54:47.71 ctrip.english
# print(type(result))
# <class 'str'>
# print(len(result))
# 86
# lst = result.split(' ')
# print(lst, len(lst),type(lst))
# 成功拆分成了list ['23461', 'u0_a285', '', '', '', '', '', '16', '', '-4', '', '65G', '796M', '450M', 'R', '', '123', '', '10.6', '', '64:14.89', 'ctrip.english\n\x1b[m\n'] 22 <class 'list'>
lst = [i for i in result.split(' ') if i != '']
cpuinfo = lst[8]
# 对 result.split(' ') 产生的列表进行遍历,把满足条件 x != '' 的元素保留下来,生成一个新的列表
print(self.current_time+'\n'+'当前cpu使用率:'+ cpuinfo +'%'+'\n')
# 获取到了干净的列表['23461', 'u0_a285', '16', '-4', '65G', '791M', '450M', 'S', '130', '10.5', '73:59.87', 'ctrip.english\n\n']
# 目前只获取到了进程CPU使用率,后面要获取当前进程对于整体cpu使用率的贡献率
def loop(self):
for i in range(10):
self.testprocess()
time.sleep(3)
if __name__ == '__main__':
controller = Controller()
controller.loop()