app专项-获取cpu使用率

#!/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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值