#!/usr/bin/env python3 """Turn md-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) 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]] = {} 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)) 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) 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())