#!/usr/bin/env python3"""Where the speedgate app's main thread spends its time, per measured window. python3 scripts/speedgate/profile.py <folder of launch-N.profile.xml + launch-N.signposts.xml> [--top N] [--match TEXT]profile.sh writes the folder. Windows: the cold start (the process's firstmain-thread sample to the end of the ColdStartToHome signpost) and eachTapToRecordFrame interval (the first open of each kind in a process apart fromthe repeats). For each window kind it prints, averaged per window, the mainthread's busy time and the symbols with the most inclusive time; --matchprints only symbols containing TEXT (e.g. a module or type name)."""import argparseimport reimport sysimport xml.etree.ElementTreeas ETfrom collections import defaultdictfrom pathlib importPathdef rows(path):"""Each <row> of an xctrace export as {column: element}, refs resolved.""" by_id = {}# An export can carry the same table twice (one <node> each): read the first.for _, element in ET.iterparse(path, events=("end",)):if element.tag == "node":return ident = element.get("id")if ident isnotNone: by_id[ident] = elementif element.tag == "row":yield {child.tag: by_id.get(child.get("ref"), child) if child.get("ref") else child for child in element}, by_iddef frames(backtrace, by_id): out = []for frame in backtrace:if frame.tag != "frame":continue frame = by_id.get(frame.get("ref"), frame) if frame.get("ref") else frame binary = frame.find("binary")if binary isnotNoneand binary.get("ref"): binary = by_id.get(binary.get("ref")) out.append((frame.get("name") or"?", binary.get("name") if binary isnotNoneelse"?"))return outdef samples(path, thread_named="Main Thread"):"""(time ns, weight ns, frames leaf first) for every running sample of the threads whose name starts with `thread_named` ("" for every thread).""" out = []for row, by_id in rows(path): thread = row.get("thread")if thread isNoneornot (thread.get("fmt") or"").startswith(thread_named):continue state = row.get("thread-state")if state isnotNoneand state.text notin (None, "Running"):continue stack = row.get("tagged-backtrace", row.get("backtrace"))if stack isNone:continue out.append((int(row["sample-time"].text), int(row["weight"].text), frames(stack, by_id)))return outdef windows(path, first_sample):"""[(label, begin, end)] from the signposts: cold, then page opens.""" begun = {} out = [] pages = 0for row, _ in rows(path): name = row.get("signpost-name") kind = row.get("event-type")if name isNoneor kind isNone:continue at = int(row["event-time"].text)if kind.text == "Begin": begun[name.text] = atelif kind.text == "End"and name.text in begun:if name.text == "ColdStartToHome": out.append(("cold start", first_sample, at))elif name.text == "TapToRecordFrame":# SpeedApp opens todo, note, person, then each again. out.append(("page, first open"if pages < 3else"page, repeat", begun[name.text], at)) pages += 1return outdef short(name): name = re.sub(r"\(.*\)$", "", name)return name if len(name) <= 140else name[:137] + "..."def main(): parser = argparse.ArgumentParser() parser.add_argument("folder") parser.add_argument("--top", type=int, default=30) parser.add_argument("--match") parser.add_argument("--callers", help="instead of symbols, the frames N levels above the first frame containing TEXT (with --depth)") parser.add_argument("--depth", type=int, default=6) parser.add_argument("--thread", default="Main Thread", help='threads whose name starts with this ("" for all of them, to see work off the main thread)') args = parser.parse_args() folder = Path(args.folder) launches = sorted(folder.glob("launch-*.profile.xml"))ifnot launches: sys.exit(f"no launch-N.profile.xml in {folder}") count = defaultdict(int) span = defaultdict(float) busy = defaultdict(float) inclusive = defaultdict(lambda: defaultdict(float)) leaf_binary = defaultdict(lambda: defaultdict(float))for profile in launches: taken = samples(profile, args.thread) first = samples(profile)[:1] if args.thread != "Main Thread"else taken[:1]ifnot taken ornot first:continuefor label, begin, end in windows(profile.with_name(profile.name.replace(".profile.", ".signposts.")), first[0][0]): count[label] += 1 span[label] += (end - begin) / 1e6for at, weight, stack in taken:ifnot begin <= at <= end:continue ms = weight / 1e6 busy[label] += msif stack: leaf_binary[label][stack[0][1]] += msif args.callers: hit = next((i for i, (name, _) in enumerate(stack) if args.callers in name), None)if hit isNone:continue# The first frames above the asked-for one that are not# the runtime's own: who asked, not how it was answered. above = [f"{short(name)} [{binary}]"for name, binary in stack[hit + 1:]if binary notin ("libswiftCore.dylib", "libsystem_kernel.dylib")][:args.depth] inclusive[label][" < ".join(above)] += mscontinuefor symbol in {f"{short(name)} [{binary}]"for name, binary in stack}: inclusive[label][symbol] += msfor label in ("cold start", "page, first open", "page, repeat"): n = count[label]ifnot n:continue print(f"\n== {label}: {n} windows · {span[label] / n:.1f} ms long · {args.thread or "every thread"} busy {busy[label] / n:.1f} ms (per window)") print(" self time by binary: " + ", ".join( f"{binary} {ms / n:.1f}"for binary, ms in sorted(leaf_binary[label].items(), key=lambda kv: -kv[1])[:8])) shown = 0for symbol, ms in sorted(inclusive[label].items(), key=lambda kv: -kv[1]):if args.match and args.match notin symbol:continue print(f" {ms / n:8.1f} {symbol}") shown += 1if shown >= args.top:breakif __name__ == "__main__": main()