#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # From megadrive-rust-fast (MIT, the same author), unchanged but for this line and the next. """Turn md-profile's (and s32x-profile's) samples into a flat profile: self time by function (the innermost inlined frame of the interrupted instruction) and inclusive time by function (any frame of the sample, inlined ones included, counted once a sample). scripts/profile.py BINARY SAMPLES [--top N] Stdlib and binutils' addr2line only. """ from __future__ import annotations import argparse import re import subprocess from collections import Counter def short(name: str) -> str: """A demangled Rust path, its generic arguments and hash dropped.""" name = re.sub(r"::h[0-9a-f]{16}$", "", name) depth, out = 0, [] for ch in name: if ch == "<": depth += 1 if depth == 1: out.append("<..>") elif ch == ">": depth -= 1 elif depth == 0: out.append(ch) return "".join(out).replace("<..>", "") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("binary") parser.add_argument("samples") parser.add_argument("--top", type=int, default=40) # sega32x-rust-fast: who a hot function's self time comes through, and its lines. parser.add_argument("--callers", help="for samples whose self function contains this text, the callers") args = parser.parse_args() samples = [line.split() for line in open(args.samples) if line.strip()] # Return addresses point after the call; one byte back is inside it, so every # frame but the interrupted instruction is looked up one byte early. samples = [[s[0]] + [format(int(a, 16) - 1, "x") for a in s[1:]] for s in samples] queries = sorted({a for s in samples for a in s}) text = "\n".join(f"0x{a}" for a in queries) + "\n" out = subprocess.run( ["addr2line", "-f", "-i", "-C", "-a", "-e", args.binary], input=text, capture_output=True, text=True, check=True, ).stdout # fmt: skip chains: dict[str, list[str]] = {} places: dict[str, str] = {} current = None lines = out.splitlines() i = 0 while i < len(lines): line = lines[i] if line.startswith("0x"): current = format(int(line, 16), "x") chains[current] = [] i += 1 continue chains[current].append(short(line)) if len(chains[current]) == 1 and i + 1 < len(lines): places[current] = lines[i + 1].rsplit("/", 1)[-1] i += 2 # function, then file:line own, inclusive = Counter(), Counter() for sample in samples: own[chains.get(sample[0], ["?"])[0]] += 1 seen = set() for a in sample: for function in chains.get(a, []): seen.add(function) for function in seen: inclusive[function] += 1 total = len(samples) if args.callers: callers, where = Counter(), Counter() for sample in samples: inner = chains.get(sample[0], ["?"]) if args.callers not in inner[0]: continue outer = [f for a in sample for f in chains.get(a, ["?"])] callers[" < ".join(outer[1:4])] += 1 where[places.get(sample[0], "?")] += 1 print(f"{sum(where.values())} samples with self in {args.callers!r}\ncallers") for chain, count in callers.most_common(args.top): print(f"{100 * count / total:6.2f}% {chain}") print("lines") for place, count in where.most_common(args.top): print(f"{100 * count / total:6.2f}% {place}") return 0 print(f"{total} samples") print("\nself") for function, count in own.most_common(args.top): print(f"{100 * count / total:6.2f}% {function}") print("\ninclusive") for function, count in inclusive.most_common(args.top): print(f"{100 * count / total:6.2f}% {function}") return 0 if __name__ == "__main__": raise SystemExit(main())