Cotton code
158 lines · 6.6 KB · PythonRaw
#!/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.ElementTree as ETfrom collections import defaultdictfrom pathlib import Pathdef 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 is not None:            by_id[ident] = element        if 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 is not None and binary.get("ref"):            binary = by_id.get(binary.get("ref"))        out.append((frame.get("name") or "?", binary.get("name") if binary is not None else "?"))    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 is None or not (thread.get("fmt") or "").startswith(thread_named):            continue        state = row.get("thread-state")        if state is not None and state.text not in (None, "Running"):            continue        stack = row.get("tagged-backtrace", row.get("backtrace"))        if stack is None:            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 = 0    for row, _ in rows(path):        name = row.get("signpost-name")        kind = row.get("event-type")        if name is None or kind is None:            continue        at = int(row["event-time"].text)        if kind.text == "Begin":            begun[name.text] = at        elif 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 < 3 else "page, repeat", begun[name.text], at))                pages += 1    return outdef short(name):    name = re.sub(r"\(.*\)$", "", name)    return name if len(name) <= 140 else 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"))    if not 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]        if not taken or not first:            continue        for label, begin, end in windows(profile.with_name(profile.name.replace(".profile.", ".signposts.")), first[0][0]):            count[label] += 1            span[label] += (end - begin) / 1e6            for at, weight, stack in taken:                if not begin <= at <= end:                    continue                ms = weight / 1e6                busy[label] += ms                if stack:                    leaf_binary[label][stack[0][1]] += ms                if args.callers:                    hit = next((i for i, (name, _) in enumerate(stack) if args.callers in name), None)                    if hit is None:                        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 not in ("libswiftCore.dylib", "libsystem_kernel.dylib")][:args.depth]                    inclusive[label][" < ".join(above)] += ms                    continue                for symbol in {f"{short(name)}  [{binary}]" for name, binary in stack}:                    inclusive[label][symbol] += ms    for label in ("cold start", "page, first open", "page, repeat"):        n = count[label]        if not 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 = 0        for symbol, ms in sorted(inclusive[label].items(), key=lambda kv: -kv[1]):            if args.match and args.match not in symbol:                continue            print(f"  {ms / n:8.1f}  {symbol}")            shown += 1            if shown >= args.top:                breakif __name__ == "__main__":    main()