可測(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文件,并算出平均值、最大值、最小值。示例截圖如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-638843.html
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)!