Perfetto Python API

0.16.0 · active · verified Tue Apr 14

The `perfetto` Python library provides APIs and bindings for Perfetto (perfetto.dev), an open-source system profiling, app tracing, and trace analysis platform. It allows users to interact with the Perfetto Trace Processor, enabling the use of Python's rich data analysis ecosystem for processing traces. Currently, the library is in an 'Alpha' development stage (v0.16.0), indicating ongoing development and potential API changes. Releases are made periodically to introduce new features and address issues.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `TraceProcessor` with a Perfetto trace file and query for basic slice events. It uses a `with` statement for proper resource management. Ensure you replace the placeholder trace file path with a valid Perfetto trace.

import os
from perfetto.trace_processor import TraceProcessor

# NOTE: Replace 'path/to/your/trace.perfetto-trace' with an actual trace file path.
# You can generate a sample trace using the Perfetto UI (ui.perfetto.dev) or Android systrace.
trace_file = os.environ.get('PERFETTO_TRACE_FILE', 'path/to/your/trace.perfetto-trace')

try:
    # Initialize TraceProcessor with a trace file
    with TraceProcessor(trace=trace_file) as tp:
        print(f"Successfully loaded trace from {trace_file}")

        # Query for slices (a common trace event type)
        qr_it = tp.query('SELECT ts, dur, name FROM slice LIMIT 5')

        print("\nFirst 5 slices:")
        for row in qr_it:
            print(f"  Timestamp: {row.ts}, Duration: {row.dur}, Name: {row.name}")

except Exception as e:
    print(f"Error processing trace: {e}")
    print("Please ensure 'path/to/your/trace.perfetto-trace' exists and is a valid Perfetto trace.")

view raw JSON →