使用 Macrobenchmark 库自动进行衡量

我们建议使用 Jetpack Macrobenchmark 来测试应用在已启用基准配置文件时的性能,然后将这些结果与已停用基准配置文件时的基准进行比较。通过这种方式,您可以测量应用启动用时(初步显示用时和完全显示用时)或运行时渲染性能(以查看生成的帧是否会导致卡顿)。

借助 Macrobenchmark,您可以通过 CompilationMode API 控制预衡量编译。若要衡量结果,您需将 compilationMode 参数设为正确的值,如以下代码段所示:

@RunWith(AndroidJUnit4ClassRunner::class)
class ColdStartupBenchmark {
    @get:Rule
    val benchmarkRule = MacrobenchmarkRule()

    @Test
    fun startupNoCompilation() = startup(CompilationMode.None())

    @Test
    fun startupBaselineProfile() = startup(CompilationMode.Partial())

    @Test
    fun startupFullCompilation() = startup(CompilationMode.Full())

    private fun startup(compilationMode: CompilationMode) = benchmarkRule.measureRepeated(
        packageName = "com.example.macrobenchmark.target",
        metrics = listOf(StartupTimingMetric()),
        compilationMode = compilationMode,
        iterations = 10,
        startupMode = StartupMode.COLD,
        setupBlock = {
            pressHome()
        }
    ) {
        // Waits for the first rendered frame, which represents time to initial display.
        startActivityAndWait()

        // Waits for content to be visible, which represents time to fully drawn.
        device.wait(Until.hasObject(By.res("my-content")), 5_000)
    }
}

您可直接在 Android Studio 中查看结果,如以下在 Google Pixel 7 上运行 Now in Android 示例应用的屏幕截图所示。从结果中可看出,使用基准配置文件时的应用启动用时最短(275.1 毫秒),比无编译时的用时(378.6 毫秒)还短。请注意,完整的 AOT 编译可能需要更长的时间(393 毫秒),因为系统需要从磁盘加载更大的文件。

ColdStartupBenchmark 结果显示,就初始显示用时来说,无编译 = 393 毫秒,完整编译 = 393 毫秒,基准配置文件 = 275 毫秒

请注意,前面的示例只是显示了使用 StartupTimingMetric 捕获的应用启动结果,还有其他需要考虑的重要指标,例如 FrameTimingMetric。 您可以参阅捕获指标,详细了解所有类型的指标。