Android simpleperf生成火焰图

8,071 阅读2分钟
1、什么是simpleperf

Simpleperf 是 Android 的原生 CPU 分析工具。 它可用于分析 Android 应用程序和在 Android 上运行的本机进程。 它可以在 Android 上分析 Java 和 C++ 代码。 simpleperf 可执行文件可以在 Android >=L 上运行,而 Python 脚本可以在 Android >= N 上使用。

Simpleperf 是 Android 开源项目的一部分。 源代码在这里。 最新的文档在这里

2、什么是火焰图

火焰图是基于 perf 结果产生的 SVG 图片,用来展示进程在一段时间 CPU 的调用栈。

3、如何使用simpleperf生成火焰图

3.1 使用top命令查看系统中cpu占用比较高的进程

Tasks: 265 total,   1 running, 264 sleeping,   0 stopped,   0 zombie
  Mem: 16777216T total, 16777216T used,   669576K free,  34742272 buffers
 Swap:   524284K total,    262144 used,   524028K free,  1382884K cached
400%cpu  52%user   0%nice  19%sys 323%idle   0%iow   6%irq   0%sirq   0%host
   PID USER         PR  NI VIRT  RES  SHR S[%CPU] %MEM     TIME+ ARGS
   334 audioserver  20   0  79M  34M  13M S 45.1   0.9  22:28.34 android.hardware.audio.service-droidlogic
  3698 root         20   0  11M 3.4M 2.7M R 16.1   0.0   0:00.07 top -n 5
   399 root         20   0  72M  29M  24M S  6.4   0.8   2:31.09 tvserver
  3630 root         20   0    0    0    0 I  3.2   0.0   0:12.92 [kworker/3:0-events]
  3626 system       30  10  13M 2.8M 2.1M S  3.2   0.0   0:11.76 logcat -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 2048 -n 25+
  3595 root         20   0    0    0    0 I  3.2   0.0   0:06.15 [kworker/1:2-events_freezable]
   348 root         20   0  27M 4.6M 3.7M S  3.2   0.1   1:13.28 android.hardware.mcuapimanager@1.0-service
   335 system       20   0  20M 5.8M 3.7M S  3.2   0.1   0:13.60 android.hardware.avmanager@1.0-service

3.2 使用simpleperf采集数据

//示例中的 " -p 348 " 指的是需要分析的进程号 
//" -g " 意味着抓取的数据含有堆栈信息
simpleperf record -p 348 -g --duration 10 -o /mnt/media_rw/sda1/simpleperf_mcu.data

3.3 将simpleperf_mcu.data拷贝到系统源码目录android/system/extras/simpleperf/scripts/

cd android/system/extras/simpleperf/scripts/
python report_sample.py simpleperf_mcu.data > simpleperf_mcu_report.data

3.4 从github中获取如下工具

git clone https://github.com/brendangregg/FlameGraph.git

3.5 生成火焰图

cd FlameGraph
./stackcollapse-perf.pl ../simpleperf_mcu_report.data > simpleperf_mcu_report_fold.data
./flamegraph.pl simpleperf_mcu_report_fold.data > simpleperf_mcu_report_fold.svg
生成的p.svg需要用Google Chrome打开

image.png