アプリ主導のプロファイリング

このページでは、ProfilingManager API を使用してシステム トレースを記録する方法について説明します。

ProfilingManager は他のプロファイル タイプも記録できます。このプロセスはシステム トレースの記録と似ていますが、各タイプで異なるビルダーが使用されます。サポートされているプロファイルとそのビルダーは次のとおりです。

  • システム トレース: SystemTraceRequestBuilder を使用して記録されます。レイテンシの分析や一般的なパフォーマンスのデバッグに役立ちます。

  • ヒープダンプ: JavaHeapDumpRequestBuilder を使用して記録されます。メモリリークの検出と最適化に役立ちます。

  • ヒープ プロファイル: HeapProfileRequestBuilder を使用して記録されます。メモリの最適化に役立ちます。

  • コールスタック プロファイル: StackSamplingRequestBuilder を使用して記録されます。これは、コード実行とレイテンシ分析を理解するうえで役立ちます。

依存関係を追加する

ProfilingManager API を最大限に活用するには、build.gradle.kts ファイルに次の Jetpack ライブラリを追加します。

Kotlin

   dependencies {
       implementation("androidx.tracing:tracing-ktx:2.0.2")
       implementation("androidx.core:core:1.19.0")
   }
   

Groovy

   dependencies {
       implementation 'androidx.tracing:tracing:2.0.2'
       implementation 'androidx.core:core:1.19.0'
   }
   

システム トレースを記録する

必要な依存関係を追加したら、次のコードを使用してシステム トレースを記録します。この例は、メインスレッドから重いオペレーションを安全に管理しながら、コンポーザブルからプロファイリング セッションを開始する方法を示しています。

Kotlin

@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
@Composable
fun ProfiledScreen(modifier: Modifier = Modifier) {
    // Use the application context: requestProfiling resolves the ProfilingManager
    // system service from it, so there's no reason to hand it a short-lived Activity.
    val appContext = LocalContext.current.applicationContext
    val scope = rememberCoroutineScope()

    Button(
        onClick = {
            // Run the orchestration off the main thread. Profiling a heavy operation
            // on the UI thread would freeze the UI (ANR) and distort the very metrics
            // you're trying to capture.
            //
            // Note: this scope is tied to composition. If the user leaves this screen
            // mid-session, the coroutine is cancelled and stopSignal.cancel() might not
            // run, but setDurationMs() acts as a safety net and ends the trace.
            scope.launch(Dispatchers.Default) {
                val callbackExecutor = Dispatchers.IO.asExecutor()
                val resultCallback = Consumer<ProfilingResult> { profilingResult ->
                    if (profilingResult.errorCode == ProfilingResult.ERROR_NONE) {
                        Log.d("ProfileTest", "Result file: ${profilingResult.resultFilePath}")
                    } else {
                        // errorMessage explains the failure (e.g., rate limiting); keep it.
                        Log.e(
                            "ProfileTest",
                            "Profiling failed errorCode=${profilingResult.errorCode} " +
                                "errorMessage=${profilingResult.errorMessage}"
                        )
                    }
                }

                val stopSignal = CancellationSignal()
                val requestBuilder = SystemTraceRequestBuilder().apply {
                    setCancellationSignal(stopSignal)
                    setTag("FOO") // Caller-supplied tag for identification.
                    setDurationMs(60000) // Hard cap: ends the session if cancel() never fires.
                    setBufferFillPolicy(BufferFillPolicy.RING_BUFFER)
                    setBufferSizeKb(32768)
                }

                // 1. Start the session. This is asynchronous system IPC. The tracing
                //    engine takes a moment to start and allocate buffers.
                requestProfiling(appContext, requestBuilder.build(), callbackExecutor, resultCallback)

                // 2. The API exposes no "profiling started" signal, so pad with a short,
                //    best-effort delay before running the code you care about. This is
                //    approximate. Increase it on slower or heavily loaded devices.
                delay(STARTUP_PADDING_MS)

                // 3. The session is already recording every thread in your app. This slice
                //    doesn't scope what's captured. It just labels this region of the
                //    timeline so heavyOperation() is easier to find. trace { } closes the
                //    section even if the block throws.

                trace("MyApp:HeavyOperation") {
                    heavyOperation()
                }

                // 4. Stop recording. Until this fires or the setDurationMs() cap is
                //    reached (whichever comes first), the session keeps capturing app-wide
                //    activity.

                stopSignal.cancel()
            }
        }
    ) {
        Text("Run & Profile Heavy Operation")
    }
}

// Best-effort wait for the system trace engine to initialize before profiling.
// There is no deterministic start callback; tune this for your target devices.
private const val STARTUP_PADDING_MS = 100L

fun heavyOperation() {
    // Background computations 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());
            setupProfileUploadWorker(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(32768);
  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 を作成して、プロファイリング結果を受け取るスレッドを定義します。プロファイリングはバックグラウンドで行われます。非 UI スレッド エグゼキュータを使用すると、後でコールバックに処理を追加する場合に、アプリケーション応答なし(ANR)エラーを防ぐことができます。

  2. プロファイリング結果を処理します。Consumer<ProfilingResult> オブジェクトを作成します。システムは、このオブジェクトを使用して、ProfilingManager からアプリにプロファイリング結果を返送します。

  3. プロファイリング リクエストを作成します。SystemTraceRequestBuilder を作成して、プロファイリング セッションを設定します。このビルダーを使用すると、ProfilingManager トレース設定をカスタマイズできます。ビルダーのカスタマイズは省略可能です。カスタマイズしない場合、システムはデフォルト設定を使用します。

    • タグを定義します。setTag() を使用して、トレース名にタグを追加します。このタグはトレースの特定に役立ちます。
    • 省略可: 期間を設定します。setDurationMs() を使用して、プロファイリングの時間をミリ秒単位で指定します。たとえば、60000 は 60 秒のトレースを設定します。指定された期間が経過する前に CancellationSignal がトリガーされない場合、トレースは指定された期間が経過すると自動的に終了します。
    • バッファ ポリシーを選択します。setBufferFillPolicy() を使用して、トレースデータの保存方法を定義します。BufferFillPolicy.RING_BUFFER は、バッファが満杯になると、新しいデータが最も古いデータを上書きし、最近のアクティビティの連続した記録を保持することを意味します。
    • バッファサイズを設定します。setBufferSizeKb() を使用して、トレースのバッファサイズを指定します。このバッファサイズを使用して、出力トレース ファイルのサイズを制御できます。
  4. 省略可: セッションのライフサイクルを管理します。CancellationSignal を作成します。このオブジェクトを使用すると、いつでもプロファイリング セッションを停止できるため、セッションの長さを正確に制御できます。

  5. 開始して結果を受け取ります。requestProfiling() を呼び出すと、ProfilingManager がバックグラウンドでプロファイリング セッションを開始します。プロファイリングが完了すると、ProfilingResultresultCallback#accept メソッドに送信されます。プロファイリングが正常に終了すると、ProfilingResultProfilingResult#getResultFilePath を介して、トレースがデバイスに保存されたパスを提供します。このファイルは、プログラムで取得することも、ローカル プロファイリングの場合はパソコンから adb pull <trace_path> を実行して取得することもできます。

  6. カスタム トレースポイントを追加します。アプリのコードにカスタム トレースポイントを追加できます。前のコード例では、trace("MyApp:HeavyOperation") { ... } ブロックは生成されたプロファイルにカスタム スライスを作成します。