Android性能測試——應用內存測試
獲取內存值,生成內存趨勢
1.如何獲取內存的值,可以參考本人之前寫的文章https://blog.csdn.net/zly_ir/article/details/105707618
2.在瞭解如何獲取內存值得基礎上,我們可以在測試應用的過程中,全程記錄應用的內存使用情況,寫入文件中,如使用如下指令:
#1秒輸出一次top使用情況,輸出使用量排名前5的應用的情況
adb shell top -d 1 > D:\DailyWork\top.log
如在測試過程中,記錄的top文件內容結果如下
可以將需要的內容用腳本處理出來,比如,抽取出com.android.systemui的cpu和RSS使用量,以python腳本爲例:
def process_log(self):
"""
處理輸入的日誌
:return: 是否處理成功
"""
try:
process_name = 'com.android.systemui'
with open('D:/DailyWork/top.log', 'r+', encoding='utf-8', errors='ignore') as f:
file_director = 'D:/DailyWork/result/'
if not os.path.isdir(file_director):
os.makedirs(file_director)
try:
f_memory = open(file_director + '/' + process_name + '.mem.txt', 'w+')
f_cpu = open(file_director + '/' + process_name + '.cpu.txt', 'w+')
# 控制應用的
system_mem_cpu_line_number = 0
process_mem_cpu_line_number = 0
# 按行讀文件,遇到相應應用的信息,則進行處理
for line in f.readlines():
if ('User' in line) and ('System' in line):
system_mem_cpu_line_number = system_mem_cpu_line_number + 1
if process_name in line:
process_mem_cpu_line_number = process_mem_cpu_line_number + 1
while process_mem_cpu_line_number < system_mem_cpu_line_number:
process_mem_cpu_line_number = process_mem_cpu_line_number + 1
f_cpu.write('0\n')
f_memory.write('0\n')
tmp = line.split()
f_cpu.write(self.replace_str(tmp[2]) + '\n') # cpu值的位置可以自行確定,不一定是第二列
f_memory.write(self.replace_str(tmp[6]) + '\n')
# 如果進程從未啓動,也寫入0值至文件夾
while process_mem_cpu_line_number < system_mem_cpu_line_number:
process_mem_cpu_line_number = process_mem_cpu_line_number + 1
f_cpu.write('0\n')
f_memory.write('0\n')
f_memory.flush()
f_memory.close()
f_cpu.flush()
f_cpu.close()
except IOError as err:
print("File write error:" + str(err))
return False
except IOError as err:
print('File read error:' + str(err))
return False
return True
處理後得到內存的值如下:
得到值就可以自己放excel裏生成趨勢圖,觀察內存使用情況,或者使用python腳本生成趨勢圖
import matplotlib
# 畫折線圖
def draw_line_img(xlabel, ylabel, xticks, y_tuple_list, img_path, figure_size):
plot.figure(figsize=figure_size, frameon=False)
plot.xlabel(xlabel)
plot.ylabel(ylabel)
for label, y_list, line_color in y_tuple_list:
plot.plot(tuple(range(len(xticks))), y_list, line_color, label=label)
plot.legend(fontsize=10)
plot.margins(0.08)
plot.savefig(img_path)
plot.close()
x_mem = []
y_mem = []
with open('D:/DailyWork/result/com.android.systemui.mem.txt', 'r+', encoding='utf-8', errors='ignore') as f:
x_index = 0
for line in f.readlines():
x_index = x_index + 1
x_mem.append(x_index)
y_mem.append(float(line) / 1024) # 轉換成MB
draw_line_img(u'時間軸', u'Mem使用情況(MB)', x_mem, [("MEM", y_mem, 'lightskyblue')], "D:/DailyWork/result/mem_line.png", (15, 5))
生成的折線圖如下:
從折線圖中可以初步斷定是否有明顯的內存泄露發生。
對於疑似的內存泄露,可以使用leakCanary進行檢測,關於leakCanary的使用,會在後續的文章進行介紹。