kolinfluence's picture
publish tree_phase.py (engine e265bbf)
d98952d verified
Raw History Blame Contribute Delete
4.84 kB
#!/usr/bin/env python3
"""Process-TREE census: same numbers as phase.py but summed over a parent and
ALL descendants, so a harness (llama-bench spawning llama-cli) can be compared
with a single-binary engine on the same axis.
Samples /proc/<pid>/task/*/stat for every process in the tree at ~40 Hz and
reports per phase the same fields phase.py reports, with `cpu_ms` summed over
every thread of every process. `EFF = cpu_ms / wall_ms` is then directly
comparable between a single process and a forked harness.
"""
import argparse, collections, json, os, time
CLK = os.sysconf("SC_CLK_TCK")
def read_utime_state(path):
try:
s = open(path).read()
except OSError:
return None
lp = s.rfind(")")
r = s[lp + 2:].split()
try:
return int(r[11]) + int(r[12]), r[0]
except (IndexError, ValueError):
return None
def wchan(pid, tid):
try:
return open(f"/proc/{pid}/task/{tid}/wchan").read().strip()
except OSError:
return ""
def children_map():
"""pid -> list of child pids"""
m = collections.defaultdict(list)
for d in os.listdir("/proc"):
if not d.isdigit():
continue
try:
st = open(f"/proc/{d}/stat").read()
lp = st.rfind(")")
ppid = int(st[lp + 2:].split()[1])
m[ppid].append(int(d))
except (OSError, IndexError, ValueError):
continue
return m
def tree(root):
m = children_map()
out, stack = [], [root]
while stack:
p = stack.pop()
out.append(p)
stack.extend(m.get(p, []))
return out
def io_bytes(root):
r = rb = 0
for p in tree(root):
try:
for line in open(f"/proc/{p}/io"):
k, _, v = line.partition(":")
if k.strip() == "rchar":
r += int(v)
elif k.strip() == "read_bytes":
rb += int(v)
except (OSError, ValueError):
pass
return r, rb
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--procname", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--interval", type=float, default=0.025)
ap.add_argument("--max-secs", type=float, default=3600)
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
root = None
t0 = time.time()
while root is None and time.time() - t0 < 60:
for d in os.listdir("/proc"):
if not d.isdigit():
continue
try:
if open(f"/proc/{d}/comm").read().strip() == a.procname:
root = int(d)
break
except OSError:
continue
if root is None:
time.sleep(0.005)
if root is None:
print("tree_phase: no root", flush=True)
return
t_start = time.monotonic()
rows = []
prev = {}
while True:
now = time.monotonic() - t_start
if now > a.max_secs:
break
pids = tree(root)
if not pids:
break
cpu = 0
running = 0
futex = 0
nthreads = 0
for p in pids:
try:
tids = os.listdir(f"/proc/{p}/task")
except OSError:
continue
for tid in tids:
got = read_utime_state(f"/proc/{p}/task/{tid}/stat")
if got is None:
continue
ticks, state = got
key = (p, tid)
d = ticks - prev.get(key, ticks)
prev[key] = ticks
cpu += d
nthreads += 1
if state == "R":
running += 1
elif "futex" in wchan(p, tid):
futex += 1
r, rb = io_bytes(root)
rows.append((round(now, 4), len(pids), nthreads, running, futex, cpu, r, rb))
time.sleep(a.interval)
wall = now if rows else 0.0
cpu_ms = (rows[-1][5] - rows[0][5]) / CLK * 1000.0 if len(rows) > 1 else 0.0
eff = cpu_ms / (wall * 1000.0) if wall else 0.0
fut_pct = 100.0 * sum(r[4] for r in rows) / max(1, sum(r[2] for r in rows))
run_pct = 100.0 * sum(1 for r in rows if r[3] <= 1) / len(rows)
out = dict(root=root, wall_s=round(wall, 3), cpu_ms=round(cpu_ms, 1),
EFF=round(eff, 3), futex_pct=round(fut_pct, 1),
one_thread_pct=round(run_pct, 1),
rchar_MB=round((rows[-1][6] - rows[0][6]) / 1e6, 1),
read_bytes_MB=round((rows[-1][7] - rows[0][7]) / 1e6, 1),
nprocs_max=max(r[1] for r in rows), nthr_max=max(r[2] for r in rows))
print(json.dumps(out))
json.dump(out, open(os.path.join(a.out, "tree_phase.json"), "w"), indent=1)
if __name__ == "__main__":
main()