Simpleperf分析之Android系统篇

【译】Simpleperf分析之Android系统篇

译者按:

Simpleperf是用于Native的CPU性能分析工具,主要用来分析代码执行耗时。本文是主文档的一部分,系统篇。

原文见aosp仓库:android_platform_profiling.md

Simpleperf主文档见aosp仓库:Simpleperf

官网介绍://developer.android.com/ndk/guides/simpleperf

目录

通用技巧

这里有一些技巧给有root权限的Android系统开发者:

  1. 运行 adb root后, simpleperf可用于分析系统范围内任何进程。
  2. 如果不是在主分支上工作,建议使用AOSP main中最新的simpleperf。脚本位置在 system/extras/simpleperf/scripts,二进制程序在system/extras/simpleperf/scripts/bin/android.
  3. 推荐使用 app_profiler.py 抓trace,然后用 report_html.py 生成html报告。 下面是一个示例。
# Record surfaceflinger process for 10 seconds with dwarf based call graph. More examples are in
# scripts reference in the doc.
$ python app_profiler.py -np surfaceflinger -r "-g --duration 10"

# Generate html report.
$ python report_html.py
  1. 从 Android >= O 开始系统库默认有符号表,我们不需要用$ANDROID_PRODUCT_OUT/symbols 中未striped二进制文件来抓了。 但是,在报告中添加源代码和反汇编(带有行号)时需要它们。下面是一个例子。
# Doing recording with app_profiler.py or simpleperf on device, and generates perf.data on host.
$ python app_profiler.py -np surfaceflinger -r "--call-graph fp --duration 10"

# Collect unstripped binaries from $ANDROID_PRODUCT_OUT/symbols to binary_cache/.
$ python binary_cache_builder.py -lib $ANDROID_PRODUCT_OUT/symbols

# Report source code and disassembly. Disassembling all binaries is slow, so it's better to add
# --binary_filter option to only disassemble selected binaries.
$ python report_html.py --add_source_code --source_dirs $ANDROID_BUILD_TOP --add_disassembly \
  --binary_filter surfaceflinger.so

在system_server进程上抓simpleperf

有时我们希望在发生特殊情况时抓系统进程。在这种情况下,我们可以在检测到情况的点处添加SimplEperf的代码。

  1. 关掉selinux adb shell setenforce 0。因为selinux只允许simpleperf在shell或debuggable/profileable 应用中使用。
  2. 在检测到特殊情况的地方添加下面的代码。
try {
  // for capability check
  Os.prctl(OsConstants.PR_CAP_AMBIENT, OsConstants.PR_CAP_AMBIENT_RAISE,
           OsConstants.CAP_SYS_PTRACE, 0, 0);
  // Write to /data instead of /data/local/tmp. Because /data can be written by system user.
  Runtime.getRuntime().exec("/system/bin/simpleperf record -g -p " + String.valueOf(Process.myPid())
            + " -o /data/perf.data --duration 30 --log-to-android-buffer --log verbose");
} catch (Exception e) {
  Slog.e(TAG, "error while running simpleperf");
  e.printStackTrace();
}

硬件 PMU 计数器限制

监视指令和缓存相关的性能事件时 (在list命令列出的hw/cache/raw/pmu 类别),这些事件被映射到每个cpu核心上的PMU计数器。但每个核心只有有限数量的PMU计数器。如果事件数量 > PMU计数器的数量,然后计数器在事件之间多路复用,这可能不是我们想要的。

在Pixel设备上,每个核上的PMU计数器的数量通常是7个,其中4个被内核用于监视内存延迟。所以只有3个计数器可用。可以同时监控最多3个PMU事件。要监视3个以上的事件,可以使用 --use-devfreq-counters 选项借用内核使用的计数器。