Skip to main content

OpenHarmony htrace file parser & cold-start analyzer

Project description

ohos-htrace

Pure-Python parser & cold-start analyzer for OpenHarmony .htrace trace files.

No external binaries needed โ€” replaces the C++ trace_streamer tool with a native Python implementation that parses .htrace protobuf data directly into an in-memory SQLite database.


โœจ Features

  • ๐Ÿš€ Pure Python โ€” no streamer.exe dependency, works on any platform
  • โšก Fast โ€” parses 120MB htrace in ~3 seconds
  • ๐ŸŽฏ Cold-start analysis โ€” automatic detection of app launch timing
  • ๐Ÿ“Š Keyword breakdown โ€” measure time spent in specific functions
  • ๐Ÿ”ง CLI & API โ€” use from command line or import in your Python code
  • ๐Ÿ“ฆ pip installable โ€” pip install ohos-htrace

๐Ÿ“ฆ Installation

pip install ohos-htrace

Or install from source:

git clone https://github.com/peng-yg/ohos-htrace.git
cd ohos-htrace
pip install -e .

๐Ÿš€ Quick Start

Command Line

# Basic cold-start analysis
ohos-htrace trace.htrace com.example.app

# With keyword duration breakdown
ohos-htrace trace.htrace aweme -k AppSpawn,LaunchAbility,LoadModule

# JSON output (for scripting)
ohos-htrace trace.htrace aweme --json

# Verbose output with top-10 functions
ohos-htrace trace.htrace aweme -k AppSpawn,LaunchAbility -v

Example output:

Parsing trace.htrace (118.7 MB) ...
Done in 3.6s

  Process:       ss.hm.ugc.aweme (pid=4575)
  Cold Start:    2566.08 ms
  Callstack:     69,933 nodes
  Depth-0:       16,916 blocks
  Max Gap:       27.9 ms
  Frames:        0

  Keyword Durations:
    AppSpawn: 19.12ms (5 hits)
    LaunchAbility: 3175.94ms (2 hits)
    LoadModule: 1164.25ms (3 hits)

Python API

import ohos_htrace

# One-shot analysis
result = ohos_htrace.parse_and_analyze(
    "trace.htrace",
    "aweme",
    keywords=["AppSpawn", "LaunchAbility", "LoadModule"],
)

print(f"Cold start: {result['cold_start_ms']:.2f}ms")
print(f"Max gap: {result['max_gap_ms']:.1f}ms")

for kw, info in result["keyword_durations"]["by_keyword"].items():
    print(f"  {kw}: {info['total_ms']:.2f}ms ({info['count']} hits)")

Low-Level API

import ohos_htrace

# Step 1: Parse htrace โ†’ in-memory SQLite
conn = ohos_htrace.parse_to_memory_db("trace.htrace")

# Step 2: Query like a normal database
cur = conn.cursor()
cur.execute("SELECT name, pid FROM process")
for name, pid in cur.fetchall():
    print(f"  {name} (pid={pid})")

# Step 3: Use analysis functions
procs = ohos_htrace.find_matching_processes(conn, "aweme")
for proc in procs:
    tree = ohos_htrace.get_process_callstack(conn, proc["id"])
    cold_ms, gaps = ohos_htrace.compute_cold_start_time(tree)
    print(f"  {proc['name']}: {cold_ms:.2f}ms")

conn.close()

๐Ÿ“ Database Schema

The in-memory database mirrors the C++ trace_streamer output:

Table Columns Description
process id, name, pid Process list
thread id, ipid, name, tid Thread list (ipid โ†’ process.id)
callstack id, callid, parent_id, name, depth, ts, dur Function call stack (callid โ†’ thread.id)
frame_slice id, vsync, ts, dur, type_desc, flag, ipid Frame rendering data

๐Ÿ” How It Works

.htrace file
    โ”‚
    โ”œโ”€ 1024-byte Header (magic: OHOSPROF)
    โ”‚
    โ””โ”€ Segments: [4-byte length][protobuf payload]
         โ”‚
         โ””โ”€ ProfilerPluginData
              โ”‚
              โ””โ”€ ftrace-plugin โ†’ TracePluginResult
                   โ”‚
                   โ”œโ”€ ftrace_cpu_detail[].event[]
                   โ”‚    โ”œโ”€ print_format (B|E|S|F events โ†’ callstack)
                   โ”‚    โ”œโ”€ task_rename_format (โ†’ process names)
                   โ”‚    โ””โ”€ sched_switch_format (โ†’ thread names)
                   โ”‚
                   โ””โ”€ comm_dict[] (โ†’ thread name resolution)

Key implementation details:

  • tgid extraction from buf โ€” Uses the tgid from B|<tgid>|<name> (not event.tgid), matching C++ streamer behavior. This is critical for correct process attribution after fork().
  • Event sorting โ€” Events from different CPU cores are sorted by (tgid, pid, ts) before B/E stack matching, preventing cross-core timing artifacts.
  • Async events โ€” Supports S|F (async start/finish) events with cookie-based pairing.

๐Ÿ†š Comparison with trace_streamer (C++)

Tested on a 118.7MB htrace file:

Metric trace_streamer ohos-htrace Match
Cold Start 2566.08 ms 2566.08 ms โœ…
Max Gap 27.9 ms 27.9 ms โœ…
AppSpawn 19.12ms (5) 19.12ms (5) โœ…
LaunchAbility 3175.94ms (2) 3175.94ms (2) โœ…
JsAbilityStage 1575.63ms (5) 1575.63ms (5) โœ…
LoadModule 1164.25ms (3) 1164.25ms (3) โœ…
Parse Time 4.6s 3.6s โšก faster
Callstack 71,114 69,933 ~98% (binder events)

Remaining differences: binder transaction events (~1,181 entries) and frame_slice data (from hidump-plugin, not yet parsed). These do not affect cold-start analysis accuracy.

๐Ÿ“‹ Requirements

  • Python โ‰ฅ 3.10
  • protobuf โ‰ฅ 4.21.0

๐Ÿ“„ License

Apache License 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ohos_htrace-0.1.0.tar.gz (47.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ohos_htrace-0.1.0-py3-none-any.whl (71.5 kB view details)

Uploaded Python 3

File details

Details for the file ohos_htrace-0.1.0.tar.gz.

File metadata

  • Download URL: ohos_htrace-0.1.0.tar.gz
  • Upload date:
  • Size: 47.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for ohos_htrace-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f87a45342c02171b95a33db04894ab81975e6a5adf3f0dbfcd4e33fea20f7ed7
MD5 48b8fbd0b9c8684e1387f8655d749bd5
BLAKE2b-256 1ba78a05471caf6e90c1fd8b5bb20087697a9f959860030483fe12ce106003db

See more details on using hashes here.

File details

Details for the file ohos_htrace-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: ohos_htrace-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 71.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for ohos_htrace-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e2cd7bf7ef361615024f45dcaed2c51682c76cb1e654b6d16fbb78a7df1c21aa
MD5 804628dc838c1b6264fe55db1955076a
BLAKE2b-256 58339bb99b7b0a9502581da2c9090439bbf2d8acb53b1340e1ecf55ddea590e6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page