Android性能优化–Perfetto分析native内存泄露
本地首发地址 https://h89.cn/archives/24.html
本文示例是windows,这里使用了python工具,在Linux和mac同样适用
前置要求
- Android 10 或更高版本
- 如果不是userdebug版本的Android系统,需要在应用的manifest中标记为profileable或debuggable
使用步骤
-
首先安装python3环境,参见 https://www.python.org/downloads/
-
下载 perfetto ,地址在 https://github.com/google/perfetto
后面需要用到这里的perfetto\tools\heap_profile
本文放在了目录D:\tools\perfetto
-
抓取一次某个应用的内存命令如下,注意提前关闭其它adb程序,如AS
python D:\tools\perfetto\tools\heap_profile -n com.app.package.name
这里只能抓到一次内存的快照。
首次运行会有如下联网下载
Downloading https://commondatastorage.googleapis.com/perfetto-luci-artifacts/v32.1/windows-amd64/traceconv.exe
如果下载失败,Windows系统请 从连接下载 并参考里面说明放文件。
或者参考如下,修改tools/heap_profile
中 curl 下载方式diff --git a/tools/heap_profile b/tools/heap_profile @@ -243,8 +243,9 @@ def download_or_get_cached(file_name, url, sha256): if needs_download: # Either the filed doesn't exist or the SHA256 doesn't match. tmp_path = bin_path + '.tmp' + proxy_7890='http://127.0.0.1:7890' print('Downloading ' + url) - subprocess.check_call(['curl', '-f', '-L', '-#', '-o', tmp_path, url]) + subprocess.check_call(['curl', '-f', '-L', '-#', '-x', proxy_7890, '-o', tmp_path, url]) with open(tmp_path, 'rb') as fd: actual_sha256 = hashlib.sha256(fd.read()).hexdigest() if actual_sha256 != sha256:
-
连续抓取多次内存快照
adb shell killall -USR1 heapprofd
需要Root权限,上一步骤不要停止
每执行一次,上一步会记录一次
这里我上传了一份自己抓的数据,下载地址 https://download.csdn.net/download/CSqingchen/87321798 -
使用
perfetto
分析抓到的raw-trace
文件,即从 https://ui.perfetto.dev/ 打开raw-trace
文件
通过点击方块,对比不同时刻的内存。每个方块对应于在该时间点收集的分配和调用堆栈的快照。
可以看到第一个大块有内存一直上升,结合其中的栈堆,分析并解决即可。
有时很小泄露,不容易看出,可以反复很多次操作应用后,对比前后数据。
下载资源raw-trace.02
是解决问题后,抓取的tarce,可以看到问题已解决。
数据视图说明
生成的profile数据包含四个视图:
- Unreleased malloc size:从记录开始到当前时间点,在此调用堆栈上分配但未释放的字节数
- Total malloc size:从记录开始到当前时间点,在此调用堆栈上分配的总字节数(包括已释放的)
- Unreleased malloc count:从记录开始到当前时间点,在此调用堆栈上没有匹配释放的分配数
- Total malloc count:从记录开始到当前时间点,在此调用堆栈上的总分配数(包括有匹配释放的)
相关问题思考
- AndroidStudio Profile 也可以Dump内存,但内存分析没有这个直接
- LeakCanary 也可以分析内存,主要是用来分析View视图,没法分析这个native内存的数据
相关文章
Android性能优化–Perfetto抓取trace
Android性能优化–perfetto分析native内存泄露
Android性能优化–Perfetto用SQL性能分析
参考文档
https://perfetto.dev/docs/data-sources/native-heap-profiler