#!/usr/bin/env python3
"""What else runs on the GPU (any context / VkDevice) while a given pass runs.
python3 -I tools/perf/nsys_overlap.py CAPTURE.sqlite "Render Depth Pre-Pass"
Rules out (or finds) contention from dc-terrain's own device, the ocean's local device, etc.
"""
import collections, re, sqlite3, sys
db = sqlite3.connect(sys.argv[1])
target = sys.argv[2]
rows = db.execute(
"select w.start, w.end, w.contextId, coalesce(s.value,'') from VULKAN_WORKLOAD w "
"left join StringIds s on s.id=w.textId order by w.start").fetchall()
tg = [r for r in rows if r[3].startswith(target)]
print(f"{len(tg)} '{target}' workloads; contexts present: {sorted(set(r[2] for r in rows))}")
ov, dur = collections.Counter(), []
for s, e, ctx, n in tg[-200:]:
dur.append((e - s) / 1e6)
for s2, e2, c2, n2 in rows:
if s2 >= e:
break
if e2 <= s or (s2 == s and n2 == n):
continue
ov[(c2, re.sub(r' \(L-?\d+\)', '', n2) or '<unlabelled>')] += (min(e, e2) - max(s, s2)) / 1e6
dur.sort()
if dur:
print(f"target duration median {dur[len(dur) // 2]:.2f} ms over last {len(dur)}")
for (c, n), t in ov.most_common(10):
print(f" ctx {c}: {t / len(dur):7.2f} ms/instance overlapping {n}")