#!/usr/bin/env python3
"""Per-frame cost of each labelled GPU pass (summed within a frame), median and p90.
python3 -I tools/perf/nsys_pass_median.py CAPTURE.sqlite [TOP]
Frames are bounded by vkQueuePresentKHR; labels come from VULKAN_WORKLOAD.textId (NOT
nameId) and need the engine's --gpu-markers. "(Ln)" level suffixes are folded together.
"""
import bisect, collections, re, sqlite3, statistics as st, sys
db = sqlite3.connect(sys.argv[1])
top = int(sys.argv[2]) if len(sys.argv) > 2 else 16
pres = [r[0] for r in db.execute(
"select v.start from VULKAN_API v join StringIds s on s.id=v.nameId "
"where s.value='vkQueuePresentKHR' order by v.start")]
per = collections.defaultdict(collections.Counter)
for s, e, n in db.execute(
"select w.start, w.end, s.value from VULKAN_WORKLOAD w join StringIds s on s.id=w.textId "
"where s.value != ''"):
f = bisect.bisect_right(pres, s)
if 0 < f < len(pres):
per[re.sub(r' \(L-?\d+\)', '', n)][f] += (e - s) / 1e6
nf = len(pres) - 1
out = []
for n, c in per.items():
v = [c.get(f, 0.0) for f in range(1, nf)]
out.append((st.median(v), sorted(v)[int(.9 * len(v))], n))
for m, p90, n in sorted(out, reverse=True)[:top]:
print(f"{m:7.2f} ms median {p90:7.2f} p90 {n}")