国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

可測(cè)含多進(jìn)程的app-- python調(diào)用adb命令獲取Android App應(yīng)用的性能數(shù)據(jù):CPU、GPU、內(nèi)存、電池、耗電量(含python源碼)

這篇具有很好參考價(jià)值的文章主要介紹了可測(cè)含多進(jìn)程的app-- python調(diào)用adb命令獲取Android App應(yīng)用的性能數(shù)據(jù):CPU、GPU、內(nèi)存、電池、耗電量(含python源碼)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

可測(cè)含多進(jìn)程的app–Python–通過(guò)adb命令獲取Android App應(yīng)用的性能數(shù)據(jù):CPU、GPU、內(nèi)存、電池、耗電量,并與Perfdog取值對(duì)比結(jié)果


1、原理

python腳本通過(guò)os.popen()方法運(yùn)行adb命令,獲取性能數(shù)據(jù),將性能數(shù)據(jù)保存在csv文件并算出均值、最大值、最小值。
本腳本可測(cè)試一個(gè)app包含多個(gè)進(jìn)程的場(chǎng)景,可以獲取每個(gè)進(jìn)程的性能數(shù)據(jù)

2、環(huán)境準(zhǔn)備:

2.1 軟件環(huán)境

具備python環(huán)境,Android環(huán)境
需要python庫(kù):os, csv, time, datetime, sys,time,pandas

2.2 手機(jī)狀態(tài)

1、Wi-Fi模式連接手機(jī)
2、統(tǒng)一手機(jī)環(huán)境變量:手機(jī)滿電,將手機(jī)降至常溫(每個(gè)測(cè)試場(chǎng)景取接近的初始溫度),屏幕亮度和音量調(diào)為50%
3、殺掉其他進(jìn)程
4、手機(jī)溫度:腳本獲取到的是電池溫度(Perfdog也是如此)。溫槍測(cè)溫:可將溫槍調(diào)整為測(cè)物體模式測(cè)溫,每次選取相同測(cè)試溫點(diǎn),測(cè)溫點(diǎn)可選攝像頭附近,不要直對(duì)攝像頭。溫槍測(cè)的和電池溫度相近。
(手機(jī)降溫:可以使用冰塊、小風(fēng)扇,或者將手機(jī)放入冰箱降溫)

3、獲取性能指標(biāo)

統(tǒng)一說(shuō)明:以下adb命令在Mac電腦上使用的是‘grep’,在windows電腦執(zhí)行時(shí)改為‘findstr’

3.1 同時(shí)會(huì)用到的其他adb命令

# Wi-Fi模式連接手機(jī),手機(jī)與電腦連接同一個(gè)Wi-Fi,查看手機(jī)IP地址,執(zhí)行命令:
adb connect 192.168.88.152
# 如果連接失敗,可以執(zhí)行如下命令重啟端口5555,再重新連接
adb tcpip 5555

# 獲取app應(yīng)用名
adb shell dumpsys window | grep mCurrentFocus
# 獲取進(jìn)程ID
adb shell ps | grep im.zego.zegoland

# 取出 文件指定行數(shù) 區(qū)間內(nèi)容
os.popen("sed -n '{},{}p' {} > {}".format(sed_count['start_count'], sed_count['end_count'], original_path,result_path))

3.2 性能指標(biāo)相關(guān)匯總表

性能指標(biāo) 在.csv文件中的名稱(chēng) 可測(cè)目標(biāo) 與Perfdog對(duì)比 adb命令
電池百分比、
電池溫度
battery_precent、
temperature[-°C]
手機(jī) 相同 adb shell dumpsys battery
耗電量:總、
屏幕、CPU、攝像頭、Wi-Fi、系統(tǒng)服務(wù)、傳感器、麥克風(fēng)
‘battery_sum[mAh]’,
‘battery_screen[mAh]’,
‘battery_cpu[mAh]’,
‘battery_camera[mAh]’,
‘battery_wifi[mAh]’,
‘battery_system_services[mAh]’,
‘battery_sensors[mAh]’,
‘battery_audio[mAh]’
整個(gè)app Perfdog計(jì)算的是功耗 # 獲取耗電量,單位:mAh,一定要WiFi模式連接手機(jī)
# 要先清空已有的耗電數(shù)據(jù)
adb shell dumpsys batterystats --enable full-wake-history
# 重置設(shè)備耗電數(shù)據(jù)
adb shell dumpsys batterystats --reset
# 執(zhí)行測(cè)試場(chǎng)景后,獲取耗電量數(shù)據(jù)
# 獲取應(yīng)用進(jìn)ID,去掉下劃線,如“u0_a901”,取值“u0a901”
# adb shell ps | grep im.zego.zegoland
獲取被測(cè)應(yīng)用的耗電量
adb shell dumpsys batterystats > batteryinfo.txt
#通過(guò)篩選關(guān)鍵字(詳細(xì)代碼中會(huì)寫(xiě))獲取耗電量所在開(kāi)始、結(jié)尾行數(shù),再通過(guò)sed命令截取區(qū)間,最后在這個(gè)sed區(qū)間內(nèi)根據(jù)uid和耗電項(xiàng)關(guān)鍵字篩選耗電量數(shù)據(jù)
CPU使用率 AppCPU[%] 接近,可替代 多進(jìn)程 # -n指定刷新次數(shù)
adb shell top -n 1 > cpuinfo.txt
# 再根據(jù)PID篩選被測(cè)app的cpu數(shù)據(jù)
GPU使用率 GUsage[%] 與PerfDog誤差在0.001位 手機(jī) # 獲取GPU數(shù)據(jù),使用第2個(gè)數(shù)除以第1個(gè)數(shù)
# 部分機(jī)型用這個(gè)命令,如一加8T,OPPO Reno6
adb shell cat /sys/class/kgsl/kgsl-3d0/gpubusy
# 部分機(jī)型用這個(gè)命令,如紅米note7
adb shell su -c ‘cat /sys/class/kgsl/kgsl-3d0/gpubusy’
內(nèi)存Pss PerfDog-Memory-Pss[MB] 與Perfdog取值相同 多進(jìn)程 # adb shell dumpsys meminfo > meminfo.txt
#通過(guò)篩選關(guān)鍵字(詳細(xì)代碼中會(huì)寫(xiě))獲取Pss所在開(kāi)始、結(jié)尾行數(shù),再通過(guò)sed命令截取區(qū)間,最后在這個(gè)sed區(qū)間內(nèi)根據(jù)PID和內(nèi)存位置獲取內(nèi)存Pss數(shù)據(jù)
內(nèi)存Uss Memory-Uss[MB] 物理專(zhuān)屬內(nèi)存,需要手機(jī)root,Perfdog獲取的是Pss / # 需要手機(jī)root
#部分手機(jī)使用如下命令
adb shell ‘procrank’
# 部分手機(jī)使用如下命令
adb shell su -c ‘procrank’

關(guān)于Android 系統(tǒng)內(nèi)存耗用:VSS/RSS/PSS/USS 的介紹,可參考:
VSS/RSS/PSS/USS 的介紹【聲網(wǎng)】

4、源碼

4.1 獲取AppCPU使用率,GPU使用率、內(nèi)存Pss、電池百分比、電池溫度、耗電量源碼

使用時(shí),根據(jù)自己測(cè)試信息修改"if main"中的appName、deviceName、性能數(shù)據(jù)文件名PerfDataFile、收集性能時(shí)間runTime(單位秒,可修改為分鐘、小時(shí)),被測(cè)進(jìn)程(可多個(gè))

#! /usr/bin/env python3
# _*_ coding:utf-8 _*_
"""
@Auth : Dora
@ Time: 2023.5.27
調(diào)整為不依賴外部方法的腳本
"""
import os, csv, time, datetime, sys
from time import sleep

import pandas as pd

class Logger(object):
    def __init__(self, filename='default.log', stream=sys.stdout):
        self.terminal = stream
        self.log = open(filename, 'a+')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass


# 將控制臺(tái)輸出到日志文件中,日志是追加模式,記得定時(shí)清理
# 便于檢驗(yàn)數(shù)據(jù)獲取是否正確。也可將這部分刪除
sys.stdout = Logger('../log/stout_log.log', sys.stdout)
sys.stderr = Logger('../log/stout.log_file', sys.stderr)


# 可用
class PertestInfo:
    def __init__(self, appName, deviceName, PerfDataFile, runTime, *progress):
        self.PerfDataFile = PerfDataFile
        # 分割線,便于定位日志
        print("{:*^50s}".format("Split Line"))
        print("{:+^50s}".format(self.PerfDataFile))

        self.appName = appName  # 要測(cè)試的app
        self.progress = progress  # 要測(cè)試的進(jìn)程,一個(gè)應(yīng)用可能有多個(gè)進(jìn)程
        print("self.progress:", self.progress, type(self.progress))
        self.deviceName = deviceName  # 設(shè)備名稱(chēng)
        self.current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        # 運(yùn)行時(shí)間
        self.run_time = datetime.timedelta(seconds=runTime)  # 收集性能數(shù)據(jù)時(shí)長(zhǎng),時(shí)間單位可修改為:hours,minutes,seconds

    def clear_getsize(self, file_path):
        # 可以寫(xiě)成一個(gè)裝飾器,待優(yōu)化
        with open(file_path,'w'):
            pass
        start_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        os.popen('adb -s {} shell top -n 1 > {}'.format(deviceName, file_path))
        while not os.path.getsize(file_path):
            # os.path.getsize() 返回文件的字節(jié)數(shù),如果為 0,則代表空
            # 判斷執(zhí)行top命令返回的數(shù)據(jù)是否存入文件,若文件為0,繼續(xù)sleep(1)
            sleep(1)
        end_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        print('運(yùn)行top命令開(kāi)始時(shí)間:', start_time)
        print('運(yùn)行top命令數(shù)據(jù)保存到文件的結(jié)束時(shí)間:', end_time)

    def get_PID(self):
        # 獲取pid
        appPID = {}
        # result = os.popen('adb -s {} shell ps | grep {}'.format(self.deviceName, appName))
        for app in self.progress:
            # print('app:', app)
            result = os.popen('adb -s {} shell ps | grep {}'.format(self.deviceName, app))
            # print("pid result:", result)
            for line in result.readlines():
                print('line:', line, type(line))
                line = '#'.join(line.split()) + '#'
                # print('line#:', line)
                appstr = app + '#'
                if appstr in line:
                    print('line#:', line)
                    pid = line.split('#')[1]
                    # print("pid:", pid)
                    appPID[app] = pid
        print('appPID:', appPID)
        sleep(1)
        return appPID

    def sed_result(self, original_path, keyword, result_path):
        # 獲取開(kāi)始、結(jié)束行數(shù)
        start_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        print('獲取start_index開(kāi)始時(shí)間:', start_time)
        sed_index = {'start_index': 0, 'end_index': 0}
        while sed_index['start_index'] == 0:
            sleep(1)
            for index, line in enumerate(open(original_path, 'r')):
                if keyword in line:
                    sed_index['start_index'] = index
                    print("start_index:", sed_index['start_index'])
                    break
        end_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        print('獲取start_index結(jié)束時(shí)間:', end_time)
        with open(original_path, 'r') as f:
            result = f.readlines()[sed_index['start_index']:]
            index = sed_index['start_index']
            for line in result:
                index = index + 1
                if line in ['\n', '\r\n']:
                    sed_index['end_index'] = index
                    print("end_index:", sed_index['end_index'])
                    break

        # 從開(kāi)始、結(jié)束行數(shù)截取內(nèi)容
        os.popen("sed -n '{},{}p' {} > {}".format(sed_index['start_index'], sed_index['end_index'], original_path,
                                                  result_path))
        # 案例:取出 / etc / passwd的第2行到第5行
        # sed - n '2,5p' / etc / passwd
        #  result = os.popen('sed -n {}p {}'.format(500, filename)).read()

    def get_batteryPercent_temperature(self):
        # 獲取電量半分比和電池溫度
        result = os.popen("adb -s {} shell dumpsys battery".format(self.deviceName))  # .read()
        # print(result)
        battery_percent = {'battery_percent': '', 'temperature': ''}
        for line in result:
            # print("line:{}-----", line)
            if "level" in line:
                battery_percent['battery_percent'] = int(line.split(":")[1])
                # print("battery_percent:{},type(battery_percent):{}".format(battery_percent, type(battery_percent)))

            if "temperature" in line:
                battery_percent['temperature'] = int(line.split(":")[1]) / 10
                # print("battery_percent:{},type(battery_percent):{}".format(battery_percent, type(battery_percent)))
        print("battery_percent:", battery_percent)
        return battery_percent

    def reset_battery(self):
        # 執(zhí)行業(yè)務(wù)場(chǎng)景前,清空耗電數(shù)據(jù),并重置設(shè)備耗電數(shù)據(jù)
        os.popen("adb -s {} shell dumpsys batterystats --enable full-wake-history".format(self.deviceName))  # 清空已有的耗電數(shù)據(jù)
        sleep(2)
        os.popen("adb -s {} shell dumpsys batterystats --reset".format(self.deviceName))  # 重置設(shè)備耗電數(shù)據(jù)

    def get_battery(self):
        # 獲取耗電量,單位:mAh
        # 一定要WiFi模式連接手機(jī)
        battery = {'battery_sum': '', 'battery_screen': '', 'battery_cpu': '', 'battery_camera': '', 'battery_wifi': '',
                   'battery_system_services': '', 'battery_sensors': '', 'battery_audio': ''}
        # 獲取進(jìn)程ID:uid
        cmd1 = "adb -s {} shell ps | grep {}".format(self.deviceName, self.appName)
        uid_data = os.popen(cmd1).read()
        uid_original = uid_data.split()[0]
        uid = uid_original.replace('_', '')
        print('uid:', uid)

        original_path = '../log/original_data.txt'
        result_path = '../log/sed_result.txt'
        # 先清空之前的內(nèi)容
        with open(original_path,'w'):
            pass
        with open(result_path,'w'):
            pass
        start_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        str1 = '  Estimated power use (mAh):'
        cmd2 = 'adb -s {} shell dumpsys batterystats > {}'.format(self.deviceName, original_path)
        os.popen(cmd2)
        while not os.path.getsize(original_path):
            # os.path.getsize() 返回文件的字節(jié)數(shù),如果為 0,則代表空
            # 耗電量數(shù)據(jù)存儲(chǔ)需要時(shí)間,判斷執(zhí)行top命令返回的數(shù)據(jù)是否存入文件
            sleep(1)
        end_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        print('運(yùn)行獲取耗電量開(kāi)始時(shí)間:', start_time)
        print('運(yùn)行耗電量數(shù)據(jù)保存到文件的結(jié)束時(shí)間:', end_time)
        self.sed_result(original_path=original_path, keyword=str1, result_path=result_path)
        while not os.path.getsize(result_path):
            sleep(1)
        with open(result_path, 'r') as f:
            for line in f.readlines():
                if uid in line:
                    print('battery_line:', line)
                    line = '#'.join(line.split())
                    battery['battery_sum'] = line.split('#')[2]
                    if 'screen=' in line:
                        battery['battery_screen'] = line.split('screen=')[1].split('#')[0]
                    if 'cpu=' in line:
                        battery['battery_cpu'] = line.split('cpu=')[1].split('#')[0]
                    if 'camera=' in line:
                        battery['battery_camera'] = line.split('camera=')[1].split('#')[0]
                    if 'wifi=' in line:
                        battery['battery_wifi'] = line.split('wifi=')[1].split('#')[0]
                    if 'system_services=' in line:
                        battery['battery_system_services'] = line.split('system_services=')[1].split('#')[0]
                    if 'sensors=' in line:
                        battery['battery_sensors'] = line.split('sensors=')[1].split('#')[0]
                    if 'audio=' in line:
                        battery['battery_audio'] = line.split('audio=')[1].split('#')[0]
        print('battery:\n', battery)
        return battery

    def get_cpuinfo(self):
        # 獲取PID
        appPID = self.get_PID()
        # print("appPID:", appPID)
        appCPU = {}
        file_path = '../log/cpuinfo.txt'
        # 先清空之前的內(nèi)容
        with open(file_path,'w'):
            pass
        start_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        os.popen('adb -s {} shell top -n 1 > {}'.format(deviceName, file_path))
        while not os.path.getsize(file_path):
            # os.path.getsize() 返回文件的字節(jié)數(shù),如果為 0,則代表空
            # 判斷執(zhí)行top命令返回的數(shù)據(jù)是否存入文件
            sleep(1)
        end_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        print('運(yùn)行top命令開(kāi)始時(shí)間:', start_time)
        print('運(yùn)行top命令數(shù)據(jù)保存到文件的結(jié)束時(shí)間:', end_time)

        with open(file_path, 'r') as f:
            for line in f.readlines():
                for app in self.progress:
                    if app in appPID.keys():
                        if appPID[app] in line:
                            # print('app:', app)
                            # print('appPID line:', line)
                            # appCPU['time'] = int(time.time())  # 當(dāng)前時(shí)間)
                            cpu = round(float(line.split()[-4]) / 8, 2)
                            appCPU[app] = cpu
        print("appCPU:", appCPU)
        return appCPU

    def get_GUsage(self):
        # 獲取GPU使用率,與PerfDog誤差在0.001以內(nèi)
        result1 = os.popen(
            'adb -s {} shell "cat /sys/class/kgsl/kgsl-3d0/gpubusy"'.format(deviceName)).read()  # 獲取GPU占用率,一加8T
        # print("result:", result1)

        result2 = os.popen('adb -s {} shell su -c "cat /sys/class/kgsl/kgsl-3d0/gpubusy"'.format(
            deviceName)).read()  # 獲取GPU占用率,紅米note7
        # print("result:", result2)

        GUsage = 0
        if result1:
            data1 = result1.split()
            GUsage = round(int(data1[0]) / int(data1[1]) * 100, 3)  # round(i,j)給i取j位小數(shù),X100,轉(zhuǎn)化為百分比
            print('GUsage1:', GUsage)
        elif result2:
            data2 = result2.split()
            GUsage = round(int(data2[0]) / int(data2[1]) * 100, 3)  # round(i,j)給i取j位小數(shù),X100,轉(zhuǎn)化為百分比
            print('GUsage2:', GUsage)
        else:
            print("GUsage獲取失敗,可能獲取GPU命令不適用于被測(cè)機(jī)型")
        return GUsage

    def get_memory_Pss(self):
        # 獲取pid
        appPID = self.get_PID()
        # 獲取內(nèi)存數(shù)據(jù)
        original_path = '../log/original_data.txt'
        result_path = '../log/sed_result.txt'
        # 先清空之前的內(nèi)容
        with open(original_path,'w'):
            pass
        with open(result_path,'w'):
            pass
        start_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())

        str1 = 'Total PSS by process:'
        cmd2 = 'adb -s {} shell dumpsys meminfo > {}'.format(self.deviceName, original_path)
        print('cmd2:', cmd2)
        os.popen(cmd2)
        while not os.path.getsize(original_path):
            # os.path.getsize() 返回文件的字節(jié)數(shù),如果為 0,則代表空
            # 判斷執(zhí)行top命令返回的數(shù)據(jù)是否存入文件
            sleep(1)
        end_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        print('運(yùn)行獲取內(nèi)存開(kāi)始時(shí)間:', start_time)
        print('運(yùn)行內(nèi)存數(shù)據(jù)保存到文件的結(jié)束時(shí)間:', end_time)
        self.sed_result(original_path=original_path, keyword=str1, result_path=result_path)
        while not os.path.getsize(result_path):
            sleep(1)
        # appPSS = {'im.zego.zegoland:zegoland_avatar': 0, 'im.zego.zegoland:zegoland_unity': 0,'im.zego.zegoland:zegoland': 0}
        appPss = {}
        with open(result_path, 'r') as f:
            for line in f.readlines():
                for app in self.progress:
                    if app in appPID.keys():
                        if appPID[app] in line:
                            # print('app:', app)
                            print('app_mem_line:', line, app, appPID[app])
                            Pss = round((int(line.strip().split('K: ')[0].replace(',', ''))) / 1024, 2)
                            # print("Pss:", Pss)
                            appPss[app] = Pss
        print("appPss", appPss)
        return appPss

    def analyse_dumpsys_Csv(self, fileName):
        # 對(duì)性能數(shù)據(jù)文件進(jìn)行計(jì)算,獲取均值、最大值、最小值
        analyse_data = []
        info = pd.read_csv(fileName, encoding='gbk')
        rowsName = info.columns  # 列名
        print('列名:', rowsName)
        lines = info.shape[0]  # 行數(shù)
        rows = info.shape[1]  # 列數(shù)
        print("行:{},type{},列:{}".format(lines, type(lines), rows))
        # result = {}
        avg_data = ['', '', '', 'avg']  # 存放均值
        max_data = ['', '', '', 'max']  # 存放最大值
        min_data = ['', '', '', 'min']  # 存放最小值
        for row_name in rowsName:
            if row_name not in ['id', 'hour', 'minute', 'second']:
                avg_value = round(info[row_name].mean(), 2)
                max_value = info[row_name].max()
                min_value = info[row_name].min()
                avg_data.append(avg_value)
                max_data.append(max_value)
                min_data.append(min_value)
        # 將均值、最大值、最小值存入analyse_data以便輸入csv文件
        analyse_data.append(avg_data)
        analyse_data.append(max_data)
        analyse_data.append(min_data)
        print('analyse_data:', analyse_data)
        # 在數(shù)據(jù)表中插入平均值、最大值、最小值
        with open(fileName, 'a+', newline='') as file:
            # a+ 追加方式寫(xiě)+讀
            writer = csv.writer(file)
            writer.writerows(analyse_data)
            sleep(1)
            file.close()

    def perf_run(self):
        # 執(zhí)行獲取數(shù)據(jù)函數(shù)
        GPU_battery_data = [
            ['id', 'hour', 'minute', 'second', 'GUsage[%]', 'battery_percent[%]', 'temperature', 'battery_sum[mAh]',
             'battery_screen[mAh]', 'battery_cpu[mAh]', 'battery_camera[mAh]', 'battery_wifi[mAh]',
             'battery_system_services[mAh]', 'battery_sensors[mAh]', 'battery_audio[mAh]']]
        print('GPU_battery_data:', GPU_battery_data)
        print("now:", datetime.datetime.now())
        print('run_time:', self.run_time)
        self.reset_battery()  # 清空耗電數(shù)據(jù),并重置耗電數(shù)據(jù)
        sleep(1)
        id = 1  # id:可以運(yùn)行的次數(shù)
        end_time = datetime.datetime.now() + self.run_time
        mem_Pss_data = []
        cpu_data = []
        while end_time > datetime.datetime.now():
            # 在指定時(shí)間內(nèi)運(yùn)行
            battery_percent = self.get_batteryPercent_temperature()  # 獲取電量百分?jǐn)?shù)和電池溫度
            print('battery_percent:', battery_percent)
            # sleep(1)
            GUsage = self.get_GUsage()  # 獲取GPU占用率
            # sleep(1)
            GPU_battery_data.append((
                str(id), str(datetime.datetime.now().hour), str(datetime.datetime.now().minute),
                str(datetime.datetime.now().second), str(GUsage),
                battery_percent['battery_percent'], battery_percent['temperature'], '', '', '', '', ''))
            cpu_info = self.get_cpuinfo()  # 獲取cpu
            cpu_info['id'] = id
            cpu_info['hour'] = datetime.datetime.now().hour
            cpu_info['minute'] = datetime.datetime.now().minute
            cpu_info['second'] = datetime.datetime.now().second

            # cpu_info['time'] = str(datetime.datetime.now().hour)+':'+str(datetime.datetime.now().minute)+':'+str(datetime.datetime.now().second)
            cpu_data.append(cpu_info)
            # sleep(1)
            mem_Pss = self.get_memory_Pss()  # 獲取內(nèi)存
            mem_Pss['id'] = id
            mem_Pss['hour'] = datetime.datetime.now().hour
            mem_Pss['minute'] = datetime.datetime.now().minute
            mem_Pss['second'] = datetime.datetime.now().second
            mem_Pss_data.append(mem_Pss)
            # print("多組Pss數(shù)據(jù):", mem_Pss_data)
            id = id + 1
            sleep(1)
        # 最后一組數(shù)據(jù)展示耗電量 mAh
        battery_percent = self.get_batteryPercent_temperature()  # 獲取電量和電池溫度
        # sleep(1)
        cpu_info = self.get_cpuinfo()  # 獲取cpu
        print('cpu_info:', cpu_info)
        cpu_info['id'] = id

        cpu_info['hour'] = datetime.datetime.now().hour
        cpu_info['minute'] = datetime.datetime.now().minute
        cpu_info['second'] = datetime.datetime.now().second

        cpu_data.append(cpu_info)
        # sleep(1)
        GUsage = self.get_GUsage()  # 獲取GPU占用率
        # sleep(1)
        mem_Pss = self.get_memory_Pss()  # 獲取內(nèi)存
        id = id + 1
        mem_Pss['id'] = id
        mem_Pss['hour'] = datetime.datetime.now().hour
        mem_Pss['minute'] = datetime.datetime.now().minute
        mem_Pss['second'] = datetime.datetime.now().second
        # print("一組Pss數(shù)據(jù):", mem_Pss)
        mem_Pss_data.append(mem_Pss)
        # print("多組Pss數(shù)據(jù):", mem_Pss_data)
        # sleep(1)
        battery = self.get_battery()  # 耗電量數(shù)據(jù),單位:mAh
        print("")
        GPU_battery_data.append((
            str(id), str(datetime.datetime.now().hour), str(datetime.datetime.now().minute),
            str(datetime.datetime.now().second), str(GUsage),
            battery_percent['battery_percent'], battery_percent['temperature'], battery['battery_sum'],
            battery['battery_screen'], battery['battery_cpu'], battery['battery_camera'], battery['battery_wifi'],
            battery['battery_system_services'], battery['battery_sensors'], battery['battery_audio']))
        print("收集性能數(shù)據(jù)結(jié)束時(shí)間:", datetime.datetime.now())
        sleep(1)
        print("保存數(shù)據(jù)")
        # 保存數(shù)據(jù)GPU和battery數(shù)據(jù)
        with open('../data/batatery_GPU-%s' % self.PerfDataFile, 'w', newline='') as file:
            writer = csv.writer(file, quoting=csv.QUOTE_ALL)
            writer.writerows(GPU_battery_data)
            sleep(10)
            file.flush()
            sleep(2)
            file.close()
        print("分析數(shù)據(jù)")

        # 分析數(shù)據(jù)
        # self.analyse_perf_Csv('../data/batatery_GPU-%s' % self.PerfDataFile)
        # 分析GPU和battery數(shù)據(jù)
        self.analyse_dumpsys_Csv('../data/batatery_GPU-%s' % self.PerfDataFile)
        # 保存內(nèi)存數(shù)據(jù)
        fieldName = []
        for app in self.progress:
            # print('app:', app)
            fieldName.append(app)
        els = ['id', 'hour', 'minute', 'second']
        fieldName = els + fieldName
        print('filedName:', fieldName)
        with open('../data/mem_Pss-%s' % self.PerfDataFile, 'w', newline='') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=fieldName)
            writer.writeheader()
            for row in mem_Pss_data:
                writer.writerow(row)
        self.analyse_dumpsys_Csv('../data/mem_Pss-%s' % self.PerfDataFile)

        # 保存cpu數(shù)據(jù)
        """
        cpu_fieldName = []
        for app in self.progress:
            # print('app:', app)
            cpu_fieldName.append(app)
        cpu_els = ['id', 'time']
        cpu_fieldName = cpu_els + cpu_fieldName
        """
        with open('../data/AppCPU-%s' % self.PerfDataFile, 'w', newline='') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=fieldName)
            writer.writeheader()
            for row in cpu_data:
                writer.writerow(row)
        self.analyse_dumpsys_Csv('../data/AppCPU-%s' % self.PerfDataFile, )


if __name__ == '__main__':
    # 一定要Wi-Fi模式連接手機(jī)
    # deviceName = '192.168.89.48:5555'
    # deviceName = '192.168.1.105:5555'
    # deviceName = '192.168.88.152:5555'  # 一加8T
    # deviceName = '192.168.88.145:5555'  # 華為P50
    deviceName = '192.168.88.210:5555'  # oppo reno6
    # deviceName = '192.168.1.106:5555'
    # deviceName = '192.168.88.192:5555'  # 小米11青春版
    # deviceName = '192.168.88.198:5555'  # 紅米note7
    # deviceName = '192.168.88.199:5555'  # oppo reno3 pro
    appName = 'im.zego.zegoland'   # ZegoLand
    # appName = 'com.zego.goavatar'  # avatar
    # 運(yùn)行時(shí)常
    runTime = 60
    PerfDataFile = "OPPOreno6-語(yǔ)聊房-{}.csv".format(
        str(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())))
    # 應(yīng)用包含多個(gè)進(jìn)程時(shí),存放于*progress
    # ZL
    phone = PertestInfo(appName, deviceName, PerfDataFile, runTime, 'im.zego.zegoland:zegoland_avatar',
                        'im.zego.zegoland:zegoland_unity',
                        'im.zego.zegoland')
    # phone = PertestInfo(appName, deviceName, PerfDataFile, runTime,'com.zego.goavatar')
    # appPID = phone.get_PID()
    # phone.get_battery()
    # phone.get_GUsage()
    # phone.get_cpuinfo()
    # phone.get_memory_Pss()
    phone.perf_run()

5、測(cè)試數(shù)據(jù)示例

測(cè)試數(shù)據(jù)輸入到csv文件,并算出平均值、最大值、最小值。示例截圖如下:
adb命令查看性能,軟件測(cè)試,android,adb,python,測(cè)試工具
adb命令查看性能,軟件測(cè)試,android,adb,python,測(cè)試工具
adb命令查看性能,軟件測(cè)試,android,adb,python,測(cè)試工具

6、使用場(chǎng)景:

1、手動(dòng)將app設(shè)置到測(cè)試場(chǎng)景,運(yùn)行性能測(cè)試腳本perftestino.py,收集性能數(shù)據(jù);
2、使用多線程,在執(zhí)行monkey測(cè)試的同時(shí)收集性能數(shù)據(jù)和log cat日志,同時(shí)檢測(cè)crash,導(dǎo)出crash日志;
3、使用多線程,在執(zhí)行UI自動(dòng)化測(cè)試場(chǎng)景的同時(shí)收集性能數(shù)據(jù)
4、手工測(cè)試功能時(shí),運(yùn)行性能測(cè)試腳本,捕捉可能存在的內(nèi)存泄露等問(wèn)題文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-638843.html

到了這里,關(guān)于可測(cè)含多進(jìn)程的app-- python調(diào)用adb命令獲取Android App應(yīng)用的性能數(shù)據(jù):CPU、GPU、內(nèi)存、電池、耗電量(含python源碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 使用adb命令啟動(dòng)app

    使用adb命令啟動(dòng)app

    1.獲取應(yīng)用包名:(方法各異自行選擇) 2.獲取正在運(yùn)行應(yīng)用的activity: ? ? 3.啟動(dòng)應(yīng)用 4.巧用monkey啟動(dòng)應(yīng)用并輸出activity ?

    2024年02月12日
    瀏覽(23)
  • ADB命令抓取安卓app日志

    ADB命令抓取安卓app日志

    前置: ?手機(jī)與電腦處于同一網(wǎng)絡(luò)下 1、電腦安裝adb 2、手機(jī)打開(kāi)開(kāi)發(fā)這模式 ? 3、用cmd連接手機(jī)--adb devices ? 4、抓取日志前先清理一下之前的日志 ????????adb logcat - c 5、輸入命令---回車(chē) ? ? ? ? adb logcat -v time C:UsersT58Desktoplog.txt 6、打開(kāi)app執(zhí)行操作 7、此時(shí)就已經(jīng)抓取到

    2024年02月16日
    瀏覽(20)
  • 通過(guò)adb命令卸載系統(tǒng)app

    通過(guò)adb命令卸載系統(tǒng)app

    在清單文件里面加入權(quán)限 ?獲取安裝app信息(沒(méi)加申請(qǐng)權(quán)限代碼,自己到權(quán)限管理里面打開(kāi)讀取應(yīng)用列表權(quán)限),然后調(diào)用下面的方法獲取應(yīng)用列表信息 運(yùn)行后,到logcat里面把打印的信息拷貝出來(lái),到此準(zhǔn)備工作就完成了 輸入adb shell,會(huì)出現(xiàn)機(jī)型,說(shuō)明成功了 ?

    2024年02月12日
    瀏覽(32)
  • [獲取手機(jī)信息]-通過(guò) ADB 命令獲取手機(jī)信息

    [獲取手機(jī)信息]-通過(guò) ADB 命令獲取手機(jī)信息

    ################################################## 目錄 通過(guò) ADB 命令獲取手機(jī)信息 ADB 常用查看命令 使用 -l 查看設(shè)備詳細(xì)信息 查看機(jī)型 查看電池狀況 查看分辨率 查看屏幕密度 查看顯示屏參數(shù) 查看 android_id 查看 IMEI 查看 Android 系統(tǒng)版本 查看 IP 地址 查看 Mac 地址 查看 CPU 信息 查看內(nèi)存

    2024年02月09日
    瀏覽(27)
  • 使用adb 命令刪除手機(jī)預(yù)裝app

    使用adb 命令刪除手機(jī)預(yù)裝app

    1. 手機(jī)開(kāi)啟開(kāi)發(fā)者選項(xiàng),允許usb調(diào)試; 2.pc 安裝adb, 1)Windows版本:https://dl.google.com/android/repository/platform-tools-latest-windows.zip 2)按鍵windows+r打開(kāi)運(yùn)行,輸入sysdm.cpl,回車(chē)。 高級(jí)》環(huán)境變量》系統(tǒng)變量》path 3)adb --version 驗(yàn)證是否成功 3.通過(guò)手機(jī)助手,華為和小米的手機(jī)助手連

    2024年02月16日
    瀏覽(22)
  • adb 獲取日志命令-史上最全

    adb logcat 獲取的是日志buffer中從頭到尾的日志,并且最新的日志會(huì)持續(xù)寫(xiě)入。歷史日志多少取決于緩沖區(qū)大小,并且我們可以通過(guò)參數(shù)過(guò)濾掉無(wú)用的日志。可以使用xlog框架將歷史日志保存(可以研究下源碼)。 日志打印不了 插拔重啟 日志緩沖區(qū)修改最大 usb驅(qū)動(dòng)查看 adb重啟

    2024年02月04日
    瀏覽(17)
  • 使用adb命令獲取手機(jī)ip地址

    最近一個(gè)項(xiàng)目需要使用adb開(kāi)啟服務(wù),然后客戶端使用安卓設(shè)備的IP地址連接到服務(wù)。 目前每次開(kāi)啟服務(wù)之后,都需要在安卓設(shè)備查看IP后輸入連接,非常的麻煩。于是我想著試用adb獲取IP,試過(guò)ifconfig等命令都沒(méi)有用。 最后我找到了以下命令: adb shell ip addr show wlan0 wlan0就是無(wú)

    2024年02月11日
    瀏覽(34)
  • 軟件測(cè)試基礎(chǔ)篇五App之a(chǎn)db命令

    軟件測(cè)試基礎(chǔ)篇五App之a(chǎn)db命令

    命令優(yōu)勢(shì):效率高 面試會(huì)問(wèn) 工具的本質(zhì)也是調(diào)用命令 解決工具的能力邊界 ADB可以用來(lái)安裝卸載軟件、管理安卓系統(tǒng)軟件、啟動(dòng)測(cè)試、抓取操作日志等 1、查看已連接的設(shè)備列表:adb devices 2、斷開(kāi)連接設(shè)備: adb disconnect 手機(jī)ip 3、無(wú)線連接設(shè)備: adb connect 手機(jī)ip(手機(jī)和電腦處于同

    2024年02月03日
    瀏覽(26)
  • Android adb命令獲取當(dāng)前Activity或者Fragment

    Android adb命令獲取當(dāng)前Activity或者Fragment

    用adb命令查看下面Demo處于 NO.3 Fragment 時(shí)的 Activity 和 Fragment 信息。 輸出結(jié)果如下: 上面的 com.example.who/com.example.who.ui.activity.SecondActivity} 可以分成兩部分看: / 前的部分是包名, / 后的部分是當(dāng)前 Activity 的類(lèi)全名。 該命令會(huì)輸出堆棧中全部的窗口信息。 輸出結(jié)果如下, Se

    2024年02月15日
    瀏覽(26)
  • android adb命令獲取處于當(dāng)前屏幕的Activity

    android adb命令獲取處于當(dāng)前屏幕的Activity 使用adb命令: ? 輸出,例如: ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities) Display #0 (activities from top to bottom): ? * Task{38ef601 #5281 type=standard A=10450:com.example.myapplication U=0 visible=true visibleRequested=true mode=fullscreen translucent=false sz=1} ? ? mResizeMo

    2024年02月15日
    瀏覽(24)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包