CN

Android Perfetto Series 2: Capturing Perfetto Traces

Word count: 2.8kReading time: 17 min
2024/05/21
loading

The previous article Android Perfetto Series 1: Introduction to Perfetto introduced what Perfetto is. This article provides a brief introduction to Perfetto capture.

Android documentation labels Systrace a legacy tool and recommends Perfetto on Android 10+. When I wrote this article, Perfetto had largely replaced Systrace in my daily work, and the OPPO and vivo teams I encountered were also migrating. This series revisits the earlier analysis methods with Perfetto.

Technical review: 2026-10-14. The main examples target Android 12+. Original 2024 screenshots remain, with older-system and newer-UI differences explained below. Commands and configuration were checked against official documentation and script source; this update adds no new device-capture results.

Table of Contents

Paul Graham said: “Either give a lot of people something they kind of want, or give a small number of people something they really want.“ Perfetto is actually something that a small number of people really want, so let’s start writing. Please join the discussion. If you spot an error or an unclear explanation, let me know so I can fix it before it misleads someone.

In this series, I want to use Perfetto to look at how apps, the Framework, and Linux work together. If you have read plenty of source code and performance articles but still find the flow hard to follow, try placing that code on a trace timeline.

Perfetto Series Catalog

  1. Android Perfetto Series Catalog
  2. Android Perfetto Series 1: Introduction to Perfetto
  3. Android Perfetto Series 2: Capturing Perfetto Traces
  4. Android Perfetto Series 3: Familiarizing with the Perfetto View
  5. Android Perfetto Series 4: Opening Large Traces via Command Line
  6. Android Perfetto Series 5: Choreographer-based Rendering Flow
  7. Android Perfetto Series 6: Why 120Hz? Advantages and Challenges
  8. Android Perfetto Series 7: MainThread and RenderThread Deep Dive
  9. Android Perfetto Series 8: Understanding Vsync and Performance Analysis
  10. Android Perfetto Series 9: Interpreting CPU Information
  11. Android Perfetto Series 10: Binder Scheduling and Lock Contention
  12. Android Perfetto Series 11: PerfettoSQL, Trace Processor and Regression Detection
  13. Android Perfetto Series 12: Trace Dataflow and Data Loss
  14. Android Perfetto Series 13: Perfetto SDK, Track Event and App Field Traces
  15. Android Perfetto Series 14: heapprofd and Memory Profiling
  16. Android Perfetto Series 15: Boot Traces and Long-running Field Tracing
  17. Android Perfetto Series 16: GPU, Power Counters and Hardware Bottlenecks
  18. Android Perfetto Series 17: Scenario Automation and Platform Tracing
  19. Android Perfetto Series 18: Input Response Latency
  20. Video (Bilibili) - Android Perfetto Basics and Case Studies
  21. Video (Bilibili) - Android Perfetto: Trace Graph Types - AOSP, WebView, Flutter + OEM System Optimization

If you haven’t seen the Systrace series yet, here is the portal:

  1. Systrace Series Catalog: Systematically introduced the use of Systrace, the predecessor of Perfetto, and used Systrace to learn and understand the basic rules of Android performance optimization and Android system operation.
  2. Personal Blog: Personal blog, mainly content related to Android, and also put some content related to life and work.

The About Me page has WeChat group information for discussing Perfetto and Android development.

Main Content

The steps for using Perfetto to analyze problems are the same as using Systrace:

  1. First you need to capture the Perfetto file
  2. Open the Trace file in ui.perfetto.dev for analysis or use the command line for analysis

I prefer capturing traces from the command line, either with my own configuration or with the official helper script. Here are the available methods.

1. Using Command Line to Capture Perfetto (Recommended)

Basic Command - adb shell perfetto

After connecting an Android device with authorized USB debugging, use its /system/bin/perfetto binary to record. This lightweight example runs in the foreground: reproduce the scenario on the phone during those 20 seconds, then run adb pull after the command finishes.

1
2
3
4
5
6
# 1. Reproduce the scenario on the phone while this command is running
adb shell perfetto -o /data/misc/perfetto-traces/trace_file.perfetto-trace -t 20s -b 64mb \
sched freq idle am wm gfx view binder_driver hal dalvik camera input res memory

# 2. After recording finishes successfully, pull the file
adb pull /data/misc/perfetto-traces/trace_file.perfetto-trace

This example records for 20 seconds with a 64 MB ring buffer. Older events are overwritten when it fills, so the file may not retain all 20 seconds. The remaining arguments select atrace categories; use adb shell atrace --list_categories to check device support. Lightweight mode mainly covers ftrace/atrace. The memory category is not a full heap dump, and this command does not automatically enable FrameTimeline or callstack sampling.

To include your app’s android.os.Trace / ATrace annotations, add --app com.example.app before the category list and replace the package name. System categories such as gfx and view do not replace app selection. After recording, check command success and the retained time range and events before opening the file in Perfetto UI. The output path is on the device; adb pull copies it to the host.

Advanced Command - adb shell perfetto with config file

With so many data sources and settings, putting everything into a command each time gets cumbersome. Save them in a configuration file (Config) and select that file when you record.

The following examples primarily target Android 12+. config.pbtx contains UTF-8 text-format TraceConfig and requires --txt; its filename extension does not determine whether its contents are text or binary.

On Android 12 and later devices

Starting from Android 12, you can directly use the /data/misc/perfetto-configs directory to store configuration files, so you don’t need to pass the configuration file through stdin. The specific command is as follows:

1
2
adb push config.pbtx /data/misc/perfetto-configs/config.pbtx
adb shell perfetto --txt -c /data/misc/perfetto-configs/config.pbtx -o /data/misc/perfetto-traces/trace.perfetto-trace

Save the pure configuration shown later as config.pbtx, then run the commands above. Reproduce the scenario while recording and pull the result after completion:

1
adb pull /data/misc/perfetto-traces/trace.perfetto-trace

On Android 10/11 (with a compatible config, for example removing the Android 12+ FrameTimeline source), or to avoid device config-path differences, a macOS/Linux shell can pass the config through standard input:

1
adb shell perfetto --txt -c - -o /data/misc/perfetto-traces/trace.perfetto-trace < config.pbtx

The host shell performs this redirection, and -c - reads stdin. Android 9’s built-in Perfetto does not support --txt and needs a binary config. Some Android 9/10 devices also require tracing services to be enabled; consult the official version and service notes rather than copying Android 12+ commands unchanged.

Source of Config

For Config, I suggest using Record new trace on ui.perfetto.dev to select and customize, and then save it to a local file. Different scenarios just load different Configs. The last part of the article talks about this in detail, you can take a look if you are interested.

Exported configurations can be shared. Start with the official examples or the basic config below, then save versions for individual scenarios.

The official repository also provides configuration examples. Check their data sources, permissions, duration, and buffer sizes before reuse; they are not universal device presets.

Precautions

  • Connection and versions: adb devices should show the target as device, not unauthorized or offline. For multiple devices, add -s DEVICE_SERIAL to raw adb commands, or --serial DEVICE_SERIAL to the helper script. Record the system version, device Perfetto version, and final config.
  • Stopping early: Ctrl+C is not reliably forwarded by a direct adb shell perfetto invocation. Exiting the host command does not establish that the device trace stopped cleanly. Use the helper script’s stop handling, or enter an interactive adb shell before running Perfetto there. The timed example can simply finish normally.
  • SELinux restrictions: On Android 12 and later, place configuration files in /data/misc/perfetto-configs; do not assume that perfetto can read a config directly from /data/local/tmp.

2. Using Perfetto Official Script to Capture (Strongly Recommended)

The official tools/record_android_trace script requires Python 3 and adb on the host PATH. It invokes the recording tool, waits, pulls the file, and normally serves it locally for the browser to open. Add --no-open to skip opening and serving, including on headless hosts. These examples were checked against the official main script on 2026-10-14; save the script version used for repeatable experiments. Android 10+ normally uses the system binary; older devices may receive a downloaded tracebox binary, so the implementation is not identical on every release.

On Linux/macOS:

1
2
3
4
curl -fLO https://raw.githubusercontent.com/google/perfetto/main/tools/record_android_trace
chmod u+x record_android_trace
./record_android_trace -o trace_file.perfetto-trace -t 10s -b 64mb \
sched freq idle am wm gfx view binder_driver hal dalvik camera input res memory

On Windows PowerShell (with Python 3 and the py launcher installed):

1
2
curl.exe -fLO https://raw.githubusercontent.com/google/perfetto/main/tools/record_android_trace
py -3 record_android_trace -o trace_file.perfetto-trace -t 10s -b 64mb sched freq idle am wm gfx view binder_driver hal dalvik camera input res memory

After downloading the script, use -c on Linux/macOS to select a config:

1
./record_android_trace -c config.pbtx -o trace_file.perfetto-trace

On Windows, use py -3 record_android_trace -c config.pbtx -o trace_file.perfetto-trace.

With -c, put duration, buffers, and data sources in the config; do not expect short options such as -t or -b to override it. The basic config below includes duration_ms. A config without a duration or another stopping condition may continue recording indefinitely.

Reproduce the scenario after the script reports that recording has started. The script can handle Ctrl+C to request a stop; wait for the pull to finish and check the file. The 2024 screenshot below uses a 30-second command, unlike the 10-second example here.

The script content can be viewed directly by visiting: https://raw.githubusercontent.com/google/perfetto/main/tools/record_android_trace

3. Using On-Device Developer Tools to Capture

When a computer or USB cable is unsuitable for the scenario, use System Tracing. It is available from Android 9 (API 28): Android 10+ records Perfetto format, while Android 9 records Systrace format. OEMs may change or hide this interface, so its settings are not identical on every phone.

Start System Tracing Application

  1. Enable Developer Options: First, make sure your device has enabled developer options. If there is no developer option in your settings, you need to find the Build number in About Phone, and then click 7 times continuously to open the developer options.

  2. Open Developer Options: Find and open developer options in the Settings menu.

  3. Start System Tracing: Scroll down in the developer options until you find “System Trace” or similar options. Click it and the system tracking application will open.

The screenshot shows the original device’s interface. Use it to recognize the feature, then check the settings available on your device.

Common settings include categories, per-CPU buffer size, debuggable applications, and a Quick Settings tile. Devices offering Long traces can also limit file size and duration. Ordinary recording uses a rolling buffer, rather than guaranteeing a complete fixed-duration recording. The app manages output files, which you export through its saved-trace notification, Files, or sharing interface; it generally does not offer an arbitrary output-path field.

Start and Stop Tracing

After configuring all the required parameters, you can start tracking by clicking the “Record trace” button. Click the “Record trace” button again to end the capture. After the capture is completed, there will usually be a prompt telling you that the capture has been completed and providing options to view or share the trace file. You can export the trace file to a computer and use the Perfetto web UI for deeper analysis.

4. Using Web Interface to Capture

When I wrote this in 2024, web recording felt finicky: sometimes it would not connect, and sometimes it complained that ADB was already using the device. I preferred recording from the command line and using the page to prepare a config. The historical screenshots remain below, with current connection options explained alongside them.

Version update: the official CHANGELOG records a rewritten recording page in v49.0 (2025-01-06). The stable UI inspected read-only for this update was v58.3-11fbaed83, with multiple transports. This is not a device-connection reliability test.

Open Record new trace, select Android, and choose a transport. WebUsb requires browser support and exclusive access to the device’s USB interface, which can conflict with a local adb server. ADB + WebSocket uses a local bridge and can coexist with other adb tools. Follow the connection instructions, authorize the phone, configure the trace, and start recording. Do not indiscriminately terminate existing ADB sessions because an old screenshot mentioned killing adb; generating a config for command-line capture is also an option.

The old entry was called Recording command. In the inspected v58.3 UI it is Cmdline instructions, with separate Shell and textproto sections. Copy or download the configuration for repeatable command-line capture.

Choose sources for the problem instead of following the old screenshot’s suggestion to select everything. UI jank often needs CPU scheduling, relevant atrace categories, and the target app. FrameTimeline additionally requires Android 12+ and the android.surfaceflinger.frametimeline source. Logcat is optional. More sources increase overhead, data volume, and the risk of losing events.

Enable Stack sampling when call stacks are needed. It depends on traced_perf, device support, and target-process permissions. User builds generally require profileable or debuggable targets; the screenshot does not grant access to arbitrary system processes. The current CPU profiling tutorial describes a newer Android 15+ workflow; older devices need configurations compatible with their recording components. Samples are discrete observations, not a record of every function call, and frequency, unwinding, and missing symbols affect the result.

Feel free to explore the other options. Later posts will cover those data sources and what they look like in a trace.

Extracting Parameters from Web Interface

Current Cmdline instructions can download textproto directly. When using an older page’s complete Shell snippet, retain only the configuration: remove the leading adb shell ..., the <<EOF wrapper, and the final standalone EOF, while keeping the config’s own braces. The old screenshot is followed by a copyable basic config below.

Save this as config.pbtx for a short UI scenario on Android 12+, replacing com.example.app with the target package. The 32 MB ring buffer is an example: old events are overwritten when it fills, so retaining all 10 seconds is not guaranteed under every workload.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
buffers {
size_kb: 32768
fill_policy: RING_BUFFER
}
duration_ms: 10000
data_sources {
config {
name: "linux.ftrace"
ftrace_config {
ftrace_events: "sched/sched_switch"
ftrace_events: "sched/sched_waking"
ftrace_events: "sched/sched_wakeup_new"
ftrace_events: "task/task_newtask"
ftrace_events: "task/task_rename"
ftrace_events: "ftrace/print"
atrace_categories: "gfx"
atrace_categories: "view"
atrace_categories: "wm"
atrace_categories: "am"
atrace_apps: "com.example.app"
}
}
}
data_sources {
config {
name: "linux.process_stats"
process_stats_config { scan_all_processes_on_start: true }
}
}
data_sources {
config { name: "android.surfaceflinger.frametimeline" }
}

This collects scheduling events, app/system annotations, initial process information, and FrameTimeline. It does not include logcat, heap profiling, or complete call stacks. After recording, confirm that the scenario lies in the retained window and the required sources produced events, then check trace-loss statistics. A file opening successfully does not prove complete recording. Long traces require separate file-streaming and capacity settings; see TraceConfig.

Reference Documents

  1. https://perfetto.dev/docs/getting-started/system-tracing
  2. https://perfetto.dev/docs/concepts/config
  3. https://developer.android.com/tools/releases/platform-tools
  4. https://mp.weixin.qq.com/s/nsqc51L5T4mrTUVsPgkj6A
  5. https://juejin.cn/post/7344983784549400613
  6. https://cs.android.com/android/platform/superproject/main/+/main:external/perfetto/test/configs/

About Me && Blog

Here is a personal introduction and related links. I hope to communicate more with my peers. When three people walk together, there must be one who can be my teacher!

  1. Blogger Personal Introduction: Contains personal WeChat and WeChat group links.
  2. This Blog Content Navigation: A navigation of personal blog content.
  3. Personal Collection of Excellent Blog Articles - Android Performance Optimization Must-Know: Welcome everyone to recommend themselves and others (WeChat private chat is fine)
  4. Android Performance Optimization Knowledge Planet: Closed in 2026; the page remains as a historical introduction.

One person can go faster, a group of people can go further

Wechat Scan

CATALOG
  1. 1. Table of Contents
  • Perfetto Series Catalog
  • Main Content
  • 1. Using Command Line to Capture Perfetto (Recommended)
    1. 1. Basic Command - adb shell perfetto
    2. 2. Advanced Command - adb shell perfetto with config file
      1. 2.1. On Android 12 and later devices
      2. 2.2. Source of Config
    3. 3. Precautions
  • 2. Using Perfetto Official Script to Capture (Strongly Recommended)
  • 3. Using On-Device Developer Tools to Capture
    1. 1. Start System Tracing Application
    2. 2. Start and Stop Tracing
  • 4. Using Web Interface to Capture
    1. 1. Extracting Parameters from Web Interface
  • Reference Documents
  • About Me && Blog