Perfetto trace чем открыть
Если при попытке открыть файл TRACE на вашем устройстве возникает ошибка, вы должны сделать две вещи - установить соответствующее программное обеспечение и связать файлы TRACE с этим программным обеспечением. Если это не решит проблему, то причина может быть другой - более подробную информацию вы найдете в этой статье.
TRACE расширение файла
- Тип файла VMware ThinApp Trace Log Format
- Разработчик файлов VMware
- Категория файла Другие файлы
- Рейтинг популярности файлов
Как открыть файл TRACE?
При открытии открытия. TRACE файлов могут быть разные причины проблем. Каждая проблема требует своего подхода, но большинство из них можно решить, следуя приведенным ниже инструкциям.
Шаг 1. Установите программу, которая поддерживает TRACE файлы
Чтобы открыть TRACE файл, в системе должна быть установлена соответствующая программа, которая поддерживает этот формат файлов. Ниже представлен список программ, которые поддерживают файлы с расширением TRACE.
Программы, открывающие файлы TRACE
Windows
Скачайте установщик для данного приложения и запустите его. После завершения установки TRACE файлы должны быть открыты с установленным приложением по умолчанию при следующей попытке открыть файл этого типа.
Помните!
Не все перечисленные приложения могут выполнять все операции с файлами TRACE. Некоторые приложения могут открывать только такой файл и просматривать его содержимое, тогда как целью других может быть преобразование файлов в другие форматы файлов. Поэтому вам следует заранее проверить возможности приложений в отношении файлов TRACE.
Шаг 2. Свяжите данное программное обеспечение с файлами TRACE
Может возникнуть ситуация, когда у пользователя есть соответствующее приложение, поддерживающее файлы TRACE, установленные в его системе, но такое приложение не связано с файлами этого типа. Чтобы связать данное приложение с TRACE файлами, пользователь должен открыть подменю файлов, щелкнув правой кнопкой мыши значок файла и выбрав опцию «Открыть с помощью». Система отобразит список предлагаемых программ, которые можно использовать для открытия файлов TRACE. Выберите соответствующую опцию и установите флажок «Всегда использовать выбранное приложение для открытия файлов такого типа». Система сохранит эту информацию, используя выбранную программу, чтобы открыть TRACE файлы.
Шаг 3. Проверьте, нет ли других ошибок, связанных с файлами TRACE
Когда вышеупомянутые решения терпят неудачу, другие варианты должны быть продолжены. Возможно, файл TRACE поврежден или поврежден. Наиболее распространенные причины повреждения файла:
Perfetto allows you to collect system-wide performance traces from Android devices from a variety of data sources (kernel scheduler via ftrace, userspace instrumentation via atrace and all other data sources listed in this site).
Data-source specific config
Alongside the trace-wide configuration parameters, the trace config also defines data-source-specific behaviors. At the proto schema level, this is defined in the DataSourceConfig section of TraceConfig :
Fields like ftrace_config , android_power_config are examples of data-source specific configs. The tracing service will completely ignore the contents of those fields and route the whole DataSourceConfig object to any data source registered with the same name.
A note on backwards/forward compatibility
The tracing service will route the raw binary blob of the DataSourceConfig message to the data sources with a matching name, without attempting to decode and re-encode it. If the DataSourceConfig section of the trace config contains a new field that didn't exist at the time when the service was built, the service will still pass the DataSourceConfig through to the data source. This allows to introduced new data sources without needing the service to know anything about them upfront.
TODO: we are aware of the fact that today extending the DataSourceConfig with a custom proto requires changing the data_source_config.proto in the Perfetto repo, which is unideal for external projects. The long-term plan is to reserve a range of fields for non-upstream extensions and provide generic templated accessors for client code. Until then, we accept patches upstream to introduce ad-hoc configurations for your own data sources.
Recording a trace through the cmdline
Prerequisites
Using the helper script
We suggest using the tools/record_android_trace script to record traces from the command line. It is the equivalent of running adb shell perfetto but it helps with getting the paths right, auto-pulling the trace once done and opening it on the browser. Furthermore, on older versions of Android it takes care of sideloading the tracebox binary to make up for the lack of tracing system services.
If you are already familiar with systrace or atrace , both cmdline tools support a systrace-equivalent syntax:
On Linux and Mac:
Using the on-device /system/bin/perfetto command
Or, if you want to use directly the on-device binary do instead:
adb shell perfetto -o /data/misc/perfetto-traces/trace_file.perfetto-trace -t 20s \ sched freq idle am wm gfx view binder_driver hal dalvik camera input res memory
Caveats when using directly the adb shell perfetto workflow:
- Ctrl+C, which normally causes a graceful termination of the trace, is not propagated by ADB when using adb shell perfetto but only when using an interactive PTY-based session via adb shell .
- On non-rooted devices before Android 12, the config can only be passed as cat config | adb shell perfetto -c - (-: stdin) because of over-restrictive SELinux rules. Since Android 12 /data/misc/perfetto-configs can be used for storing configs.
- On devices before Android 10, adb cannot directly pull /data/misc/perfetto-traces . Use adb shell cat /data/misc/perfetto-traces/trace > trace to work around.
- When capturing longer traces, e.g. in the context of benchmarks or CI, use PID=$(perfetto --background) and then kill $PID to stop.
Full trace config
The short syntax allows to enable only a subset of the data sources; for full control of the trace config, pass the full trace config in input.
See the Trace configuration page and the examples in each data source doc page for detailed instructions about how to configure all the various knobs of Perfetto.
If you are running on a Mac or Linux host, or are using a bash-based terminal on Windows, you can use the following:
WARNING: The below command does not work on Android P because the --txt option was introduced in Q. The binary protobuf format should be used instead; the details of this can be found on the Trace configuration page.
Or alternatively, when using directly the on-device command:
cat config.pbtx | adb shell perfetto -c - --txt -o /data/misc/perfetto-traces/trace.perfetto-trace
Alternatively, first push the trace config file and then invoke perfetto:
adb push config.pbtx /data/ local /tmp/config.pbtx adb shell 'cat /data/local/tmp/config.pbtx | perfetto --txt -c - -o /data/misc/perfetto-traces/trace.perfetto-trace'
NOTE: because of strict SELinux rules, on non-rooted builds of Android, passing directly the file path as -c /data/local/tmp/config will fail, hence the -c - + stdin piping above. From Android 12 (S), /data/misc/perfetto-configs/ can be used instead.
Pull the file using adb pull /data/misc/perfetto-traces/trace ~/trace.perfetto-trace and open it in the Perfetto UI.
NOTE: On devices before Android 10, adb cannot directly pull /data/misc/perfetto-traces . Use adb shell cat /data/misc/perfetto-traces/trace > trace.perfetto-trace to work around.
The full reference for the perfetto cmdline interface can be found here.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. Java is a registered trademark of Oracle and/or its affiliates.
Unlike many always-on logging systems (e.g. Linux's rsyslog, Android's logcat), in Perfetto all tracing data sources are idle by default and record data only when instructed to do so.
Data sources record data only when one (or more) tracing sessions are active. A tracing session is started by invoking the perfetto cmdline client and passing a config (see QuickStart guide for Android or Linux).
A simple trace config looks like this:
And is used as follows:
perfetto --txt -c config.pbtx -o trace_file.perfetto-trace
TIP: Some more complete examples of trace configs can be found in the repo in /test/configs/ .
NOTE: If you are tracing on Android using adb and experiencing problems, see the Android section below.
Программы, обслуживающие файл TRACE
Windows
Trace analysis
Beyond the trace recording capabilities, the Perfetto codebase includes a dedicated project for importing, parsing and querying new and legacy trace formats, Trace Processor.
Trace Processor is a portable C++11 library that provides column-oriented table storage, designed ad-hoc for efficiently holding hours of trace data into memory and exposes a SQL query interface based on the popular SQLite query engine. The trace data model becomes a set of SQL tables which can be queried and joined in extremely powerful and flexible ways to analyze the trace data.
On top of this, Trace Processor includes also a trace-based metrics subsystem consisting of pre-baked and extensible queries that can output strongly-typed summaries about a trace in the form of JSON or protobuf messages (e.g., the CPU usage at different frequency states, breakdown by process and thread).
Trace-based metrics allow an easy integration of traces in performance testing scenarios or batch analysis or large corpuses of traces.
Trace Processor is also designed for low-latency queries and for building trace visualizers. Today Trace Processor is used by the Perfetto UI as a Web Assembly module, Android Studio and Android GPU Inspector as native C++ library.
Contributing
For bugs affecting Android or the tracing internals:
Googlers: use the internal bug tracker go/perfetto-bugs
Non-Googlers: use GitHub issues.
For bugs affecting Chrome Tracing:
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. Java is a registered trademark of Oracle and/or its affiliates.
Программы, которые поддерживают TRACE расширение файла
Следующий список функций TRACE -совместимых программ. TRACE файлы можно встретить на всех системных платформах, включая мобильные, но нет гарантии, что каждый из них будет должным образом поддерживать такие файлы.
Other resources
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. Java is a registered trademark of Oracle and/or its affiliates.
Perfetto is a production-grade open-source stack for performance instrumentation and trace analysis. It offers services and libraries for recording system-level and app-level traces, native + java heap profiling, a library for analyzing traces using SQL and a web-based UI to visualize and explore multi-GB traces.
Triggers
In nominal conditions, a tracing session has a lifecycle that simply matches the invocation of the perfetto cmdline client: trace data recording starts when the TraceConfig is passed to perfetto and ends when either the TraceConfig.duration_ms has elapsed, or when the cmdline client terminates.
Perfetto supports an alternative mode of either starting or stopping the trace which is based on triggers. The overall idea is to declare in the trace config itself:
- A set of triggers, which are just free-form strings.
- Whether a given trigger should cause the trace to be started or stopped, and the start/stop delay.
Why using triggers? Why can't one just start perfetto or kill(SIGTERM) it when needed? The rationale of all this is the security model: in most Perfetto deployments (e.g., on Android) only privileged entities (e.g., adb shell) can configure/start/stop tracing. Apps are unprivileged in this sense and they cannot control tracing.
Triggers offer a way to unprivileged apps to control, in a limited fashion, the lifecycle of a tracing session. The conceptual model is:
- The privileged Consumer (see Service model), i.e. the entity that is normally authorized to start tracing (e.g., adb shell in Android), declares upfront what are the possible trigger names for the trace and what they will do.
- Unprivileged entities (any random app process) can activate those triggers. Unprivileged entities don't get a say on what the triggers will do, they only communicate that an event happened.
Triggers can be signaled via the cmdline util
(or also by starting an independent trace session which uses only the activate_triggers: "trigger_name" field in the config)
There are two types of triggers:
Start triggers
Start triggers allow activating a tracing session only after some significant event has happened. Passing a trace config that has START_TRACING trigger causes the tracing session to stay idle (i.e. not recording any data) until either the trigger is hit or the trigger_timeout_ms timeout is hit.
trace_duration_ms and triggered traces can not be used at the same time.
Stop triggers
STOP_TRACING triggers allow to prematurely finalize a trace when the trigger is hit. In this mode the trace starts immediately when the perfetto client is invoked (like in nominal cases). The trigger acts as a premature finalization signal.
This can be used to use perfetto in flight-recorder mode. By starting a trace with buffers configured in RING_BUFFER mode and STOP_TRACING triggers, the trace will be recorded in a loop and finalized when the culprit event is detected. This is key for events where the root cause is in the recent past (e.g., the app detects a slow scroll or a missing frame).
Multi-process data sources
Some data sources are singletons. E.g., in the case of scheduler tracing that Perfetto ships on Android, there is only data source for the whole system, owned by the traced_probes service.
However, in the general case multiple processes can advertise the same data source. This is the case, for instance, when using the Perfetto SDK for userspace instrumentation.
If this happens, when starting a tracing session that specifies that data source in the trace config, Perfetto by default will ask all processes that advertise that data source to start it.
In some cases it might be desirable to further limit the enabling of the data source to a specific process (or set of processes). That is possible through the producer_name_filter and producer_name_regex_filter .
NOTE: the typical Perfetto run-time model is: one process == one Perfetto Producer; one Producer typically hosts multiple data sources.
When those filters are set, the Perfetto tracing service will activate the data source only in the subset of producers matching the filter.
System-wide tracing on Android and Linux
On Linux and Android, Perfetto bundles a number of data sources that are able to gather detailed performance data from different system interfaces. For the full sets and details see the Data Sources section of the documentation. Some examples:
Kernel tracing: Perfetto integrates with Linux's ftrace and allows to record kernel events (e.g scheduling events, syscalls) into the trace.
/proc and /sys pollers, which allow to sample the state of process-wide or system-wide cpu and memory counters over time.
Integration with Android HALs modules for recording battery and energy-usage counters.
Native heap profiling: a low-overhead heap profiler for hooking malloc/free/new/delete and associating memory to call-stacks, based on out-of-process unwinding, configurable sampling, attachable to already running processes.
Java heap profiling: an out-of-process profiler tightly integrated with the Android RunTime that allows to get full snapshots of the managed heap retention graph (types, field names, retained size and references to other objects) without, however, dumping the full heap contents (strings and bitmaps) and hence reducing the serialization time and output file size.
On Android, Perfetto is the next-generation system tracing system and replaces the chromium-based systrace. ATrace-based instrumentation remains fully supported. See Android developer docs for more details.
Recording a trace
Command line tools (usage examples below in this page):
- Using the tools/record_android_trace helper script.
- Using directly the /system/bin/perfetto command on device [reference].
- Through the record page in the Perfetto UI.
- Using the on-device System Tracing App
Streaming long traces
By default Perfetto keeps the full trace buffer(s) in memory and writes it into the destination file (the -o cmdline argument) only at the end of the tracing session. This is to reduce the perf-intrusiveness of the tracing system. This, however, limits the max size of the trace to the physical memory size of the device, which is often too limiting.
In some cases (e.g., benchmarks, hard to repro cases) it is desirable to capture traces that are way larger than that, at the cost of extra I/O overhead.
To achieve that, Perfetto allows to periodically write the trace buffers into the target file (or stdout) using the following TraceConfig fields:
write_into_file (bool) : When true periodically drains the trace buffers into the output file. When this option is enabled, the userspace buffers need to be just big enough to hold tracing data between two write periods. The buffer sizing depends on the activity of the device. The data rate of a typical trace is ~1-4 MB/s. So a 16MB in-memory buffer can hold for up write periods of ~4 seconds before starting to lose data.
file_write_period_ms (uint32) : Overrides the default drain period (5s). Shorter periods require a smaller userspace buffer but increase the performance intrusiveness of tracing. If the period given is less than 100ms, the tracing service will use a period of 100ms.
max_file_size_bytes (uint64) : If set, stops the tracing session after N bytes have been written. Used to cap the size of the trace.
For a complete example of a working trace config in long-tracing mode see /test/configs/long_trace.cfg .
Summary: to capture a long trace just set write_into_file:true , set a long duration_ms and use an in-memory buffer size of 32MB or more.
Как открыть файл TRACE?
Проблемы с доступом к TRACE могут быть вызваны разными причинами. Что важно, все распространенные проблемы, связанные с файлами с расширением TRACE, могут решать сами пользователи. Процесс быстрый и не требует участия ИТ-специалиста. Мы подготовили список, который поможет вам решить ваши проблемы с файлами TRACE.
Шаг 1. Установите ThinApp программное обеспечение
Наиболее распространенной причиной таких проблем является отсутствие соответствующих приложений, поддерживающих файлы TRACE, установленные в системе. Решение простое, просто скачайте и установите ThinApp. Полный список программ, сгруппированных по операционным системам, можно найти выше. Если вы хотите загрузить установщик ThinApp наиболее безопасным способом, мы рекомендуем вам посетить сайт VMware, Inc. и загрузить его из официальных репозиториев.
Шаг 2. Убедитесь, что у вас установлена последняя версия ThinApp
Если проблемы с открытием файлов TRACE по-прежнему возникают даже после установки ThinApp, возможно, у вас устаревшая версия программного обеспечения. Проверьте веб-сайт разработчика, доступна ли более новая версия ThinApp. Может также случиться, что создатели программного обеспечения, обновляя свои приложения, добавляют совместимость с другими, более новыми форматами файлов. Если у вас установлена более старая версия ThinApp, она может не поддерживать формат TRACE. Последняя версия ThinApp должна поддерживать все форматы файлов, которые совместимы со старыми версиями программного обеспечения.
Шаг 3. Назначьте ThinApp для TRACE файлов
Если проблема не была решена на предыдущем шаге, вам следует связать TRACE файлы с последней версией ThinApp, установленной на вашем устройстве. Следующий шаг не должен создавать проблем. Процедура проста и в значительной степени не зависит от системы
Выбор приложения первого выбора в Windows
- Выберите пункт Открыть с помощью в меню «Файл», к которому можно щелкнуть правой кнопкой мыши файл TRACE.
- Далее выберите опцию Выбрать другое приложение а затем с помощью Еще приложения откройте список доступных приложений.
- Последний шаг - выбрать опцию Найти другое приложение на этом. указать путь к папке, в которой установлен ThinApp. Теперь осталось только подтвердить свой выбор, выбрав Всегда использовать это приложение для открытия TRACE файлы и нажав ОК .
Выбор приложения первого выбора в Mac OS
Шаг 4. Проверьте TRACE на наличие ошибок
Вы внимательно следили за шагами, перечисленными в пунктах 1-3, но проблема все еще присутствует? Вы должны проверить, является ли файл правильным TRACE файлом. Вероятно, файл поврежден и, следовательно, недоступен.
1. Проверьте TRACE файл на наличие вирусов или вредоносных программ.
Если случится так, что TRACE инфицирован вирусом, это может быть причиной, которая мешает вам получить к нему доступ. Немедленно просканируйте файл с помощью антивирусного инструмента или просмотрите всю систему, чтобы убедиться, что вся система безопасна. Если файл TRACE действительно заражен, следуйте инструкциям ниже.
2. Убедитесь, что файл с расширением TRACE завершен и не содержит ошибок
Если вы получили проблемный файл TRACE от третьего лица, попросите его предоставить вам еще одну копию. В процессе копирования файла могут возникнуть ошибки, делающие файл неполным или поврежденным. Это может быть источником проблем с файлом. Это может произойти, если процесс загрузки файла с расширением TRACE был прерван и данные файла повреждены. Загрузите файл снова из того же источника.
3. Проверьте, есть ли у пользователя, вошедшего в систему, права администратора.
Некоторые файлы требуют повышенных прав доступа для их открытия. Выйдите из своей текущей учетной записи и войдите в учетную запись с достаточными правами доступа. Затем откройте файл VMware ThinApp Trace Log Format.
4. Проверьте, может ли ваша система обрабатывать ThinApp
5. Убедитесь, что ваша операционная система и драйверы обновлены
Современная система и драйверы не только делают ваш компьютер более безопасным, но также могут решить проблемы с файлом VMware ThinApp Trace Log Format. Возможно, файлы TRACE работают правильно с обновленным программным обеспечением, которое устраняет некоторые системные ошибки.
Вы хотите помочь?
Если у Вас есть дополнительная информация о расширение файла TRACE мы будем признательны, если Вы поделитесь ею с пользователями нашего сайта. Воспользуйтесь формуляром, находящимся здесь и отправьте нам свою информацию о файле TRACE.
Android
On Android, there are some caveats around using adb shell
- Ctrl+C, which normally causes a graceful termination of the trace, is not propagated by ADB when using adb shell perfetto but only when using an interactive PTY-based session via adb shell .
- On non-rooted devices before Android 12, the config can only be passed as cat config | adb shell perfetto -c - (-: stdin) because of over-restrictive SELinux rules. Since Android 12 /data/misc/perfetto-configs can be used for storing configs.
- On devices before Android 10, adb cannot directly pull /data/misc/perfetto-traces . Use adb shell cat /data/misc/perfetto-traces/trace > trace to work around.
- When capturing longer traces, e.g. in the context of benchmarks or CI, use PID=$(perfetto --background) and then kill $PID to stop.
TraceConfig
The TraceConfig is a protobuf message (reference docs) that defines:
The general behavior of the whole tracing system, e.g.:
- The max duration of the trace.
- The number of in-memory buffers and their size.
- The max size of the output trace file.
Which data sources to enable and their configuration, e.g.:
For the kernel tracing data source , which ftrace events to enable.
For the heap profiler, the target process name and sampling rate.
See the data sources section of the docs for details on how to configure the data sources bundled with Perfetto.
The x mappings: which buffer each data source should write into (see buffers section below).
The tracing service ( traced ) acts as a configuration dispatcher: it receives a config from the perfetto cmdline client (or any other Consumer) and forwards parts of the config to the various Producers connected.
When a tracing session is started by a consumer, the tracing service will:
- Read the outer section of the TraceConfig (e.g. duration_ms , buffers ) and use that to determine its own behavior.
- Read the list of data sources in the data_sources section. For each data source listed in the config, if a corresponding name ( "linux.ftrace" in the example below) was registered, the service will ask the producer process to start that data source, passing it the raw bytes of the DataSourceConfig subsection verbatim to the data source (See backward/forward compat section below).
Tracing in Chromium
Perfetto has been designed from the grounds to replace the internals of the chrome://tracing infrastructure. Tracing in Chromium and its internals are based on Perfetto's codebase on all major platforms (Android, CrOS, Linux, MacOS, Windows). The same service-based architecture of system-wide tracing applies, but internally the Chromium Mojo IPC system is used instead of Perfetto's own UNIX socket.
By default tracing works in in-process mode in Chromium, recording only data emitted by Chromium processes. On Android (and on Linux, if disabling the Chromium sandbox) tracing can work in hybrid in-process+system mode, combining chrome-specific trace events with Perfetto system events.
Recording traces
At its core, Perfetto introduces a novel userspace-to-userspace tracing protocol based on direct protobuf serialization onto a shared memory buffer. The tracing protocol is used both internally for the built-in data sources and exposed to C++ apps through the Tracing SDK and the Track Event Library.
This new tracing protocol allows dynamic configuration of all aspects of tracing through an extensible protobuf-based capability advertisement and data source configuration mechanism (see Trace configuration docs). Different data sources can be multiplexed onto different subsets of user-defined buffers, allowing also streaming of arbitrarily long traces into the filesystem.
Tracing SDK and user-space instrumentation
The Perfetto Tracing SDK enables C++ developers to enrich traces with app-specific trace points. You can choose between the flexibility of defining your own strongly-typed events and creating custom data sources or using the easier-to-use Track Event Library which allows to easily create time-bounded slices, counters and time markers using annotations of the form TRACE_EVENT("category", "event_name", "x", "str", "y", 42) .
The SDK is designed for tracing of multi-process systems and multi-threaded processes. It is based on ProtoZero, a library for direct writing of protobuf events on thread-local shared memory buffers.
The same code can work both in fully-in-process mode, hosting an instance of the Perfetto tracing service on a dedicated thread, or in system mode, connecting to the Linux/Android tracing daemon through a UNIX socket, allowing to combine app-specific instrumentation points with system-wide tracing events.
The SDK is based on portable C++11 code tested with the major C++ sanitizers (ASan, TSan, MSan, LSan). It doesn't rely on run-time code modifications or compiler plugins.
Buffers
The buffer sections define the number, size and policy of the in-memory buffers owned by the tracing service. It looks as follows:
Each buffer has a fill policy which is either:
RING_BUFFER (default): the buffer behaves like a ring buffer and writes when full will wrap over and replace the oldest trace data in the buffer.
DISCARD: the buffer stops accepting data once full. Further write attempts are dropped.
WARNING: DISCARD can have unexpected side-effect with data sources that commit data at the end of the trace.
A trace config must define at least one buffer to be valid. In the simplest case all data sources will write their trace data into the same buffer.
While this is fine for most basic cases, it can be problematic in cases where different data sources write at significantly different rates.
For instance, imagine a trace config that enables both:
The kernel scheduler tracer. On a typical Android phone this records ~10000 events/second, writing ~1 MB/s of trace data into the buffer.
Memory stat polling. This data source writes the contents of /proc/meminfo into the trace buffer and is configured to poll every 5 seconds, writing ~100 KB per poll interval.
If both data sources are configured to write into the same buffer and such buffer is set to 4MB, most traces will contain only one memory snapshot. There are very good chances that most traces won't contain any memory snapshot at all, even if the 2nd data sources was working perfectly. This is because during the 5 s. polling interval, the scheduler data source can end up filling the whole buffer, pushing the memory snapshot data out of the buffer.
Dynamic buffer mapping
Data-source <> buffer mappings are dynamic in Perfetto. In the simplest case a tracing session can define only one buffer. By default, all data sources will record data into that one buffer.
In cases like the example above, it might be preferable separating these data sources into different buffers. This can be achieved with the target_buffer field of the TraceConfig.
Can be achieved with:
Recording a trace through the Perfetto UI
Navigate to ui.perfetto.dev and select Record new trace from the left menu. From this page, select and turn on the data sources you want to include in the trace. More detail about the different data sources can be found in the Data sources section of the docs.
If you are unsure, start by turning on Scheduling details under the CPU tab.
Ensure your device is connected and select Add ADB device. Once your device has successfully paired (you may need to allow USB debugging on the device), select the Start Recording button.
Allow time for the trace to be collected (10s by default) and then you should see the trace appear.
Your trace may look different depending on which data sources you enabled.
Starting the tracing services
Perfetto is based on platform services that are avilable since Android 9 (P) but are enabled by default only since Android 11 (R). On Android 9 (P) and 10 (Q) you need to do the following to ensure that the tracing services are enabled before getting started:
If you are running a version of Android older than P, you can still capture a trace with Perfetto using the record_android_trace script. See instructions below in the Recording a trace through the cmdline section.
PBTX vs binary format
There are two ways to pass the trace config when using the perfetto cmdline client format:
Text format
It is the preferred format for human-driven workflows and exploration. It allows to pass directly the text file in the PBTX (ProtoBuf TeXtual representation) syntax, for the schema defined in the trace_config.proto (see reference docs)
When using this mode pass the --txt flag to perfetto to indicate the config should be interpreted as a PBTX file:
perfetto -c /path/to/config.pbtx --txt -o trace_file.perfetto-trace
NOTE: The --txt option has been introduced only in Android 10 (Q). Older versions support only the binary format.
WARNING: Do not use the text format for machine-to-machine interaction benchmark, scripts and tools) as it's more prone to breakages (e.g. if a field is renamed or an enum is turned into an integer)
Binary format
It is the preferred format for machine-to-machine (M2M) interaction. It involves passing the protobuf-encoded binary of the TraceConfig message. This can be obtained passing the PBTX in input to the protobuf's protoc compiler (which can be downloaded here).
and then passing it to perfetto as follows, without the --txt argument:
perfetto -c config.bin -o trace_file.perfetto-trace
Trace visualization
Perfetto provides also a brand new trace visualizer for opening and querying hours-long traces, available at ui.perfetto.dev. The new visualizer takes advantage of modern web platform technologies. Its multi-threading design based WebWorkers keeps the UI always responsive; the analytical power of Trace Processor and SQLite is fully available in-browser through WebAssembly.
The Perfetto UI works fully offline after it has been opened once. Traces opened with the UI are processed locally by the browser and do not require any server-side interaction.
Читайте также: