本页介绍在使用 Microbenchmark 库时如何配置非 Gradle 构建系统。
虽然 Microbenchmark 库随附的 Gradle 插件可直接与 Android Gradle 插件集成,但您也可以在其他构建系统(例如 Bazel 或 Buck)中使用 Microbenchmark 库。
插桩
通过在测试清单的插桩代码块中指定 AndroidBenchmarkRunner
或子类,可将其用作插桩测试运行程序:
<manifest package="com.example.library.test" ...> <instrumentation android:name="androidx.benchmark.junit4.AndroidBenchmarkRunner" /> ... </manifest>
为了获得准确的测量结果,基准测试不得设置为可调试。如未正确设置可调试标志,该库会抛出错误,而不会报告无效的结果。在本地运行期间,此设置可能需要切换为 debuggable=true
,才能与 Android Studio 性能分析器搭配使用。
您可将 Microbenchmark 构建为通过以下两种方式运行:在自插桩 APK 中运行,或使用一个测试 APK 对另一个 APK 进行插桩测试。
自插桩 APK
如果使用自插桩 APK(作为 Gradle 针对 com.android.library
中 androidTest
目录的输出),则必须在单个 APK 的 Android 清单中停用可调试属性:
<manifest package="com.example.library.test" ...> <instrumentation android:name="androidx.benchmark.junit4.AndroidBenchmarkRunner" android:targetPackage="com.example.library.test"/> <application android:debuggable="false"/> </manifest>
使用测试 APK 对应用 APK 进行插桩测试
如果您的 build 会输出两个 APK,即应用 APK 和测试 APK(作为 Gradle 针对 com.android.app
软件包中 androidTest
目录的输出),则必须将应用 APK 设为 debuggable=false
。Android 操作系统会忽略测试 APK 的可调试标志。
<!-- Test manifest. --> <manifest package="com.example.android.app.test" ...> <instrumentation android:name="androidx.benchmark.junit4.AndroidBenchmarkRunner" android:targetPackage="com.example.android.app"/> <!-- This debuggable is ignored by the OS. --> </manifest> <!-- App being tested. --> <manifest package="com.example.android.app" ...> <application android:debuggable="false"/> </manifest>
Android Studio 和 Gradle 均不支持对应用模块 APK 进行微基准测试。这是因为,如果支持依赖于不可调试、经过优化或经过缩减的 APK 变体的额外测试目录,而不从基准测试向应用代码发出缩减中断调用,这会增加测试的复杂性。
编译
我们建议您在运行测试之前使用 以下命令:
adb shell cmd package compile -f -m speed com.example.benchmark
缩减和优化
建议对基准测试进行缩减和优化,以获得更接近发布版的性能。如需查看代码示例,请参阅基准测试示例项目。
代码覆盖率
我们建议基准测试应在停用代码覆盖率选项的情况下运行,而不应使用 JaCoCo 之类的工具修改任何库或 DEX。
因此,我们建议将基准测试作为与其他插桩测试隔离的源代码集,并使用发布版依赖项单独构建。在启用和不启用代码覆盖率选项的情况下,这样都可以避免多次构建测试。
基准测试所依赖的库的调试变体,尤其是在本地构建的调试变体,可能在构建时启用了代码覆盖率选项。
运行测试
您可以从命令行运行测试,并指定要搭配使用的类,如下例所示:
adb shell am instrument -w com.example.benchmark/androidx.benchmark.junit4.AndroidBenchmarkRunner
如需在不使用 Gradle 的情况下在运行时配置 Microbenchmark 库,请参阅 Microbenchmark 插桩参数。
为您推荐
编写 Microbenchmark
Plan to create quality apps and features from the start by understanding best practices and requirements.
创建基准配置文件
Plan to create quality apps and features from the start by understanding best practices and requirements.