Nacre/tools/engine-test/sample.py
astar76 10bb7f04fb engine-test: Servo vs WebKit vs Chromium comparison (RAM, CPU, GPU, site checks)
tools/engine-test: per-second process-tree sampler (PSS, CPU, DRM fdinfo GPU),
WebKitGTK 6.0 shell, drivers for Servo Nacre and old Nacre, run.sh, analyze.py.
docs/engine/engine-comparison.md: method, per-site tables, side-by-side
screenshots, caveats, conclusions and what Servo needs for parity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 23:13:52 -06:00

149 lines
6 KiB
Python
Executable file

#!/usr/bin/env python3
"""Sample a browser's whole process tree once a second into a CSV.
Usage: sample.py --out run.csv (--pid PID | --pid-file FILE | --name REGEX) [--mark FILE] [--mark-log FILE] [--until-gone]
Each row: time, the current mark (the phase the driver is in), process count, PSS of the tree (MB, from
/proc/<pid>/smaps_rollup), CPU of the tree (% of one core, from utime+stime in /proc/<pid>/stat), the GPU's busy %
(whole card, averaged over ten reads a second), the card's VRAM in use (whole card), and the tree's own GPU use from
the DRM fdinfo of its processes (amdgpu: gfx engine busy %, VRAM and GTT held by its DRM clients).
The tree is every process matching --pid / --pid-file / --name plus all their descendants, found again each second, so helper
processes (renderers, GPU, network) that come and go are counted. The mark comes from --mark (a file holding the
label) or --mark-log (the last `MARK <label>` line written to a log). With --until-gone the sampler stops one tick
after the tree is empty.
"""
import argparse
import os
import re
import time
CARD = "/sys/class/drm/card1/device"
TICK = os.sysconf("SC_CLK_TCK")
def read(path):
try:
with open(path) as f:
return f.read()
except OSError:
return ""
def processes():
"""pid -> (ppid, starttime, cpu ticks, name, cmdline)"""
out = {}
for d in os.listdir("/proc"):
if not d.isdigit():
continue
stat = read(f"/proc/{d}/stat")
if not stat:
continue
name = stat[stat.find("(") + 1:stat.rfind(")")]
f = stat[stat.rfind(")") + 2:].split()
cmd = read(f"/proc/{d}/cmdline").replace("\0", " ").strip()
out[int(d)] = (int(f[1]), int(f[19]), int(f[11]) + int(f[12]), name, cmd)
return out
def tree(procs, roots):
kids = {}
for pid, p in procs.items():
kids.setdefault(p[0], []).append(pid)
seen, todo = set(), list(roots)
while todo:
pid = todo.pop()
if pid in seen or pid not in procs:
continue
seen.add(pid)
todo.extend(kids.get(pid, []))
return seen
def pss_kb(pid):
m = re.search(r"^Pss:\s+(\d+)", read(f"/proc/{pid}/smaps_rollup"), re.M)
return int(m.group(1)) if m else 0
def drm(pids):
"""(gfx busy ns, vram KiB, gtt KiB) summed over the tree's DRM clients (each client counted once)."""
clients = {}
for pid in pids:
try:
fds = os.listdir(f"/proc/{pid}/fdinfo")
except OSError:
continue
for fd in fds:
info = read(f"/proc/{pid}/fdinfo/{fd}")
if "drm-client-id" not in info:
continue
kv = dict(re.findall(r"^([\w-]+):\s+(\d+)", info, re.M))
cid = info.split("drm-client-id:")[1].split()[0]
clients[cid] = (int(kv.get("drm-engine-gfx", 0)), int(kv.get("drm-memory-vram", 0)),
int(kv.get("drm-memory-gtt", 0)))
return clients
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--pid", type=int)
ap.add_argument("--pid-file", help="file holding the root pid, read each tick (the browser may start later)")
ap.add_argument("--name", help="regex matched against the process name and command line")
ap.add_argument("--mark")
ap.add_argument("--mark-log")
ap.add_argument("--until-gone", action="store_true")
a = ap.parse_args()
rx = re.compile(a.name) if a.name else None
me = os.getpid()
mark, log_pos = "start", 0
prev_cpu, prev_gfx, prev_t = {}, {}, time.monotonic()
seen_any = started = False
with open(a.out, "w") as out:
out.write("t,mark,procs,pss_mb,cpu_pct,gpu_busy,vram_mb,tree_gfx_pct,tree_vram_mb,tree_gtt_mb\n")
t0 = time.time()
while True:
busy = []
for _ in range(10): # gpu_busy_percent is instantaneous: average it
busy.append(int(read(f"{CARD}/gpu_busy_percent") or 0))
time.sleep(0.1)
now = time.monotonic()
dt, prev_t = now - prev_t, now
procs = processes()
pid = a.pid or int(read(a.pid_file).strip() or 0) if a.pid_file else a.pid
roots = [pid] if pid else []
roots = roots or [p for p, v in procs.items()
if p != me and rx and (rx.search(v[3]) or rx.search(v[4]))]
pids = tree(procs, roots) - {me}
cpu = {}
ticks = 0
for pid in pids:
key = (pid, procs[pid][1]) # pid + start time: a reused pid is a new process
cpu[key] = procs[pid][2]
# a process new since the last tick started within it: all its ticks count (none on the first tick)
ticks += cpu[key] - prev_cpu[key] if key in prev_cpu else cpu[key] if started else 0
prev_cpu, started = cpu, True
clients = drm(pids)
gfx_ns = sum(c[0] - prev_gfx.get(k, (c[0],))[0] for k, c in clients.items())
prev_gfx = clients
if a.mark:
mark = read(a.mark).strip() or mark
if a.mark_log:
text = read(a.mark_log)
for m in re.finditer(r"MARK (\S+)", text[log_pos:]):
mark = m.group(1)
log_pos = len(text)
pss = sum(pss_kb(p) for p in pids) / 1024
row = [f"{time.time() - t0:.1f}", mark, len(pids), f"{pss:.1f}", f"{100 * ticks / TICK / dt:.1f}",
f"{sum(busy) / len(busy):.1f}", f"{int(read(f'{CARD}/mem_info_vram_used') or 0) / 2**20:.1f}",
f"{100 * gfx_ns / 1e9 / dt:.1f}", f"{sum(c[1] for c in clients.values()) / 1024:.1f}",
f"{sum(c[2] for c in clients.values()) / 1024:.1f}"]
out.write(",".join(map(str, row)) + "\n")
out.flush()
seen_any = seen_any or bool(pids)
if a.until_gone and seen_any and not pids:
break
if __name__ == "__main__":
main()