如何捕获性能剖析文件

本页介绍了如何使用 ProfilingManager API 记录系统轨迹。

添加依赖项

为了获得最佳的 ProfilingManager API 使用体验,请将以下 Jetpack 库添加到您的 build.gradle.kts 文件中。

Kotlin

   dependencies {
       implementation("androidx.tracing:tracing:1.3.0")
       implementation("androidx.core:core:1.16.0")
   }
   

Groovy

   dependencies {
       implementation 'androidx.tracing:tracing:1.3.0'
       implementation 'androidx.core:core:1.16.0'
   }
   

录制系统跟踪记录

添加所需的依赖项后,使用以下代码记录系统轨迹。此示例展示了 Activity 中的基本设置,用于启动和管理分析会话。

Kotlin

@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
fun sampleRecordSystemTrace() {
    val mainExecutor: Executor =
        Dispatchers.IO.asExecutor() // Your choice of executor for the callback to occur on.
    val resultCallback = Consumer<ProfilingResult> { profilingResult ->
        if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
            Log.d(
                "ProfileTest",
                "Received profiling result file=" + profilingResult.resultFilePath
            )
        } else {
            Log.e(
                "ProfileTest",
                "Profiling failed errorcode=" + profilingResult.errorCode + " errormsg=" + profilingResult.errorMessage
            )
        }
    }
    val stopSignal = CancellationSignal()

    val requestBuilder = SystemTraceRequestBuilder()
    requestBuilder.setCancellationSignal(stopSignal)
    requestBuilder.setTag("FOO") // Caller supplied tag for identification
    requestBuilder.setDurationMs(60000)
    requestBuilder.setBufferFillPolicy(BufferFillPolicy.RING_BUFFER)
    requestBuilder.setBufferSizeKb(20971520)
    requestProfiling(applicationContext, requestBuilder.build(), mainExecutor, resultCallback)

    // Wait some time for profiling to start.

    Trace.beginSection("MyApp:HeavyOperation")
    heavyOperation()
    Trace.endSection()

    // Once the interesting code section is profiled, stop profile
    stopSignal.cancel()
}

fun heavyOperation() {
    // Computations you want to profile
}

Java

void heavyOperation() {
  // Computations you want to profile
}

void sampleRecordSystemTrace() {
  Executor mainExecutor = Executors.newSingleThreadExecutor();
  Consumer<ProfilingResult> resultCallback =
      new Consumer<ProfilingResult>() {
        @Override
        public void accept(ProfilingResult profilingResult) {
          if (profilingResult.getErrorCode() == ProfilingResult.ERROR_NONE) {
            Log.d(
                "ProfileTest",
                "Received profiling result file=" + profilingResult.getResultFilePath());
          } else {
            Log.e(
                "ProfileTest",
                "Profiling failed errorcode="

                    + profilingResult.getErrorCode()
                    + " errormsg="
                    + profilingResult.getErrorMessage());
          }
        }
      };
  CancellationSignal stopSignal = new CancellationSignal();

  SystemTraceRequestBuilder requestBuilder = new SystemTraceRequestBuilder();
  requestBuilder.setCancellationSignal(stopSignal);
  requestBuilder.setTag("FOO");
  requestBuilder.setDurationMs(60000);
  requestBuilder.setBufferFillPolicy(BufferFillPolicy.RING_BUFFER);
  requestBuilder.setBufferSizeKb(20971520);
  Profiling.requestProfiling(getApplicationContext(), requestBuilder.build(), mainExecutor,
      resultCallback);

  // Wait some time for profiling to start.

  Trace.beginSection("MyApp:HeavyOperation");
  heavyOperation();
  Trace.endSection();

  // Once the interesting code section is profiled, stop profile
  stopSignal.cancel();
}

示例代码通过以下步骤设置和管理分析会话:

  1. 设置执行程序。创建一个 Executor 来定义将接收分析结果的线程。性能分析在后台进行。如果您稍后向回调添加更多处理,使用非界面线程执行器有助于防止出现应用无响应 (ANR) 错误。

  2. 处理性能分析结果。创建一个 Consumer<ProfilingResult> 对象。 系统使用此对象将 ProfilingManager 中的分析结果发送回您的应用。

  3. 构建分析请求。创建 SystemTraceRequestBuilder 以设置性能剖析会话。借助此构建器,您可以自定义 ProfilingManager 轨迹设置。您可以选择自定义构建器;如果不自定义,系统会使用默认设置。

    • 定义代码。使用 setTag() 可向轨迹名称添加标记。此标记有助于您识别轨迹。
    • 可选:设置时长。使用 setDurationMs() 指定分析时长(以毫秒为单位)。例如,60000 会设置 60 秒的轨迹。如果在指定时长内未触发 CancellationSignal,跟踪会在指定时长后自动结束。
    • 选择缓冲政策。使用 setBufferFillPolicy() 定义如何存储轨迹数据。BufferFillPolicy.RING_BUFFER 表示当缓冲区已满时,新数据会覆盖最旧的数据,从而持续记录最近的活动。
    • 设置缓冲区大小。使用 setBufferSizeKb() 为跟踪指定缓冲区大小,您可以使用该参数来控制输出轨迹文件的大小。
  4. 可选:管理会话生命周期。创建 CancellationSignal。 借助此对象,您可以随时停止分析会话,从而精确控制其时长。

  5. 开始并接收结果。当您调用 requestProfiling() 时,ProfilingManager 会在后台启动性能分析会话。完成分析后,它会将 ProfilingResult 发送到您的 resultCallback#accept 方法。如果分析成功完成,ProfilingResult 会通过 ProfilingResult#getResultFilePath 提供轨迹在设备上保存的路径。您可以通过编程方式获取此文件,也可以通过在计算机上运行 adb pull <trace_path> 来获取此文件以进行本地分析。

  6. 添加自定义轨迹点。您可以在应用的代码中添加自定义轨迹点。在前面的代码示例中,使用 Trace.beginSection()Trace.endSection() 添加了名为 MyApp:HeavyOperation 的轨迹切片。此自定义切片会显示在生成的配置文件中,突出显示应用中的特定操作。