Android基于perfetto分析native内存泄露
官方文档(可在Chome直接翻译) https://perfetto.dev/docs/data-sources/native-heap-profiler
示例 raw-trace 资源地址 https://download.csdn.net/download/CSqingchen/87321798
本文示例是windows,这里使用了python工具,在Linux和mac同样适用
- 首先安装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
这里只能抓到一次内存的快照,如果想连续记录多次内存的数据需要能Root手机
首次运行会有如下联网下载Downloading https://commondatastorage.googleapis.com/perfetto-luci-artifacts/v32.1/windows-amd64/traceconv.exe
如果下载失败,请 从连接下载 并参考里面说明放文件。
或者参考如下,修改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,可以看到问题已解决 相关问题思考
- AndroidStudio Profile 也可以Dump内存,但内存分析没有这个直接
- LeakCanary 也可以分析内存,主要是用来分析View视图,没法分析这个native内存的数据