对 Microbenchmark 进行性能分析

默认情况下,Microbenchmark 可为您提供有关已执行代码的时间和分配情况的信息。如果您想调查所测量的代码运行缓慢的原因,可以在启用 CPU 性能分析器的情况下运行基准测试。选择性能分析器配置的方法如下:添加插桩运行程序参数 androidx.benchmark.profiling.mode,并指定 MethodTracingStackSamplingNone 参数之一(如以下示例所示)。如需详细了解这些选项,请参阅选择记录配置

Groovy

android {
    defaultConfig {
        // must be one of: 'None', 'StackSampling', or 'MethodTracing'
        testInstrumentationRunnerArguments["androidx.benchmark.profiling.mode"]= 'StackSampling'
    }
}

Kotlin

android {
    defaultConfig {
        // must be one of: 'None', 'StackSampling', or 'MethodTracing'
        testInstrumentationRunnerArguments["androidx.benchmark.profiling.mode"] = "StackSampling"
    }
}

当您对基准测试进行性能分析后,系统会将输出 .trace 文件连同 JSON 结果一起复制到主机的目录下。只需在 Android Studio 中依次点击 File > Open 打开此文件,即可在 CPU 性能分析器中检查性能分析结果。

MethodTracing

对于方法跟踪,基准测试会在捕获方法轨迹之前进行预热,并记录基准测试调用的每种方法。不过,捕获每种方法进入/退出操作的开销会显著影响性能结果。

StackSampling

对于堆栈采样,基准测试会在预热完成后对调用堆栈进行采样。您可以使用插桩参数控制采样频率采样时长

在 Android 10 (API 29) 及更高版本中,堆栈采样使用 Simpleperf 对应用调用堆栈(包括 C++ 代码)进行采样。在 Android 9 (API 28) 及更低版本中,它使用 Debug.startMethodTracingSampling 来捕获堆栈样本。

您可以通过添加其他插桩参数来配置此性能分析模式:

  • androidx.benchmark.profiling.sampleFrequency

    • 每秒要捕获的堆栈样本数
    • 参数类型:整数
    • 默认为每秒 1000 个样本。
  • androidx.benchmark.profiling.sampleDurationSeconds

    • 基准测试的运行时长。
    • 参数类型:整数
    • 默认为 5 秒。

None

不捕获性能分析文件,但仍然会测量有关时间和分配情况的信息。