鸣谢:首先感谢之前一位大佬(jianjianjianbing (煎饼))分享的代码,里面有用到这位大佬曾封装好的一部分 adb 代码,再次感谢
思路:在循环中定义好循环间隔,每 N 秒获取一次当前 APP 的内存情况,这里用 adb 可以容易获取到,并将数据写入到 excel 中,结束后,在 excel 中做表看内存峰值,以及内存释放情况(这部分代码也能做表,但是实现时没有考虑过,现在也没想继续改 QAQ)
以下是代码实现:(初次尝试用程序做点事情很激动,但是感觉代码部分是在存在丑陋的地方,发出来也想讨论进步。谢谢大家,希望不至于辣眼睛)
import subprocess
import time
import xlwt
from xlutils.copy import copy
from xlrd import open_workbook
def run_cmd(cmd):
"""执行CMD命令"""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return [i.decode() for i in p.communicate()[0].splitlines()]
def get_apk_info():
"""获取apk的package,activity名称
:return: list eg ['com.android.calendar', 'com.meizu.flyme.calendar.AllInOneActivity']
"""
result = run_cmd("adb shell dumpsys activity top")
for line in result:
if line.strip().startswith('ACTIVITY'):
return line.split()[1].split('/')
def get_mem_using(package_name=None):
"""查看apk的内存占用
:param package_name:
:return: 单位KB
"""
if not package_name:
package_name = get_apk_info()[0]
results = run_cmd("adb shell dumpsys meminfo {}".format(package_name))
for index, result in enumerate(results):
if result.strip().startswith('Java Heap'):
return results[index:index + 9]
def init_to_excel(dicts):
"""写入数据到excel中
:param dicts: dict
:return
"""
file = xlwt.Workbook()
table = file.add_sheet('APP_Summary', cell_overwrite_ok=True)
i = 1
j = 1
for key in dicts:
table.write(0, 0, 'times(secend)')
table.write(0, i, key)
table.col(i).width = 256 * 17
i += 1
for value in dicts.values():
table.write(1, 0, 5)
table.write(1, j, int(value))
table.col(j).width = 256 * 17
j += 1
file.save('APP_Summary.xls')
def add_to_excel(dicts, times):
r_xls = open_workbook("APP_Summary.xls") # 读取excel文件
row = r_xls.sheets()[0].nrows # 获取已有的行数
excel = copy(r_xls) # 将xlrd的对象转化为xlwt的对象
table = excel.get_sheet('APP_Summary') # 获取要操作的sheet
# 对excel表追加一行内容
j = 1
for value in dicts.values():
table.write(row, 0, int(times) * 5)
table.col(0).width = 256 * 17
table.write(row, j, int(value))
table.col(j).width = 256 * 17
j += 1
excel.save("APP_Summary.xls") # 保存并覆盖文件
def main():
dicts = {}
result = get_mem_using()
for i in result[:len(result) - 2]:
if i.strip():
dicts[i.split(':')[0].strip()] = i.split(':')[1].strip()
p = result[-1].split('TOTAL')
dicts[('TOTAL' + p[1]).split(':')[0]
] = ('TOTAL' + p[1]).split(':')[1].strip()
dicts[('TOTAL' + p[2]).split(':')[0]
] = ('TOTAL' + p[2]).split(':')[-1].strip()
return dicts
if __name__ == '__main__':
i = 1
while True:
print("写入第 {} 次数据!".format(i))
dicts = main()
if i == 1:
init_to_excel(dicts)
else:
add_to_excel(dicts, i)
time.sleep(5)
i += 1