adb 实时监控设备及应用内存使用情况

# /usr/bin/python
# encoding:utf-8
import csv
import os
import time

# 监控CPU资源信息
class MonitoringCPUResources(object):
    def __init__(self, seconds):
        #这里根据传入的时间计算需要执行的获取数据的次数,传入时间的单位为秒
        self.counter = seconds / 5
        #添加表格头
        self.alldata = [("timestamp","totalcpu", "cpustatus","meminfo")]
    # 单次执行监控过程
    def monitoring(self):
        #获取整机内存
        totalMemory = os.popen("adb shell dumpsys meminfo | grep 'Used RAM'")    
        totalMemoryValue = totalMemory.readline().split("K:")[0].strip()    
        #获取设备整体cpu使用率
        totalcpu = os.popen("adb shell dumpsys cpuinfo | grep TOTAL")
        totalcpuvalue = totalcpu.readline().split("%")[0].strip()
        #获取单个APP的cpu使用率
        cpuinfo = os.popen("adb shell dumpsys cpuinfo | grep com.hhmedic.app.patient.trtc.demo.new")
        cpuvalue = cpuinfo.readline().split("%")[0].strip()
        #获取单个APP的内存使用情况
        meminfo = os.popen("adb shell dumpsys meminfo | grep com.hhmedic.app.patient.trtc.demo.new")
        memvalue = meminfo.readline().split("K:")[0].strip()
        # #获取单个APP的pid,在单个APP每一次打开pid都会改变
        # pidinfo = os.popen("adb shell ps -ef | grep 'com.hhmedic.app.patient.trtc.demo.new' | grep -v grep | awk '{print $2}'")
        # pidvalue = pidinfo.readlines()[0].rstrip('\n')

        #将获取到的数据打印
        currenttime = self.getCurrentTime()
        # print("pid is: " + pidvalue)
        # print("current time is:"+currenttime)
        # print("totalcpu used is " + totalcpuvalue)
        # print("cpu used is:" + cpuvalue)
        print(totalMemory.readline())
        print("total memory is: " + totalMemoryValue + " ==== mem used is:" + memvalue)
        #将获取到的数据填充到性能统计表数据中,但此时并未写文件
        self.alldata.append([currenttime,totalcpuvalue,cpuvalue, memvalue])
    # 多次执行监控过程
    def run(self):
        #这里是一直重复执行获取数据的操作
        while self.counter > 0:
            self.monitoring()
            self.counter = self.counter - 1
            #将这个延迟注释掉是因为本身获取设备或APP数据是需要时间的,测试得到这个时间大概就是5秒,所有将这个延迟去除了
            # time.sleep(5)
    # 获取当前的时间戳
    def getCurrentTime(self):
        currentTime = time.strftime("%H:%M:%S", time.localtime())
        return currentTime
    # 数据的存储
    def SaveDataToCSV(self):
        csvfile = open('cpustatus03161339.csv', 'w',0)
        writer = csv.writer(csvfile)
        writer.writerows(self.alldata)
        csvfile.close()
if __name__ == "__main__":
    monitoringCPUResources = MonitoringCPUResources(7200)
    monitoringCPUResources.run()
    monitoringCPUResources.SaveDataToCSV()
0 0 投票数
文章评分
订阅评论
提醒
guest
0 评论
内联反馈
查看所有评论
京ICP备17066706号-1
0
希望看到您的想法,请您发表评论x