#!/usr/bin/env python3 """What each module of a built tree costs to elaborate, in instructions: the measure Treant's reports use (TitiSkywalker/NavierStokesAndEuler, experiments/treant-perf/det_cost.py, whose method this follows without its package). Every module of the libraries NavierStokes and Euler is elaborated once more, alone, on one thread and synchronously (`lean -j1 -DElab.async=false`, with its library's leanOptions) against the tree's own compiled files, under `perf stat -e instructions:u`. It builds nothing and writes nothing in the tree. A count does not depend on how busy the machine is, so the runs go side by side. python3 meter.py [workers] Writes module, file, instructions, seconds, exit code, a row a module; prints the total over the modules that elaborate.""" import concurrent.futures, os, subprocess, sys, tempfile, time, tomllib tree, out = sys.argv[1], sys.argv[2] workers = int(sys.argv[3]) if len(sys.argv) > 3 else os.cpu_count() or 8 lake = tomllib.load(open(f"{tree}/lakefile.toml", "rb")) flag = lambda k, v: f"-D{k}={str(v).lower() if isinstance(v, bool) else v}" common = [flag(k, v) for k, v in (lake.get("leanOptions") or {}).items()] opts = {l["name"]: common + [flag(k, v) for k, v in (l.get("leanOptions") or {}).items()] for l in lake["lean_lib"]} env = dict(os.environ, LEAN_PATH=subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=tree, capture_output=True, text=True, check=True).stdout.strip()) lean = subprocess.run(["elan", "which", "lean"], cwd=tree, capture_output=True, text=True, check=True).stdout.strip() files = [] for lib in ("NavierStokes", "Euler"): if os.path.exists(f"{tree}/{lib}.lean"): files.append((lib, f"{lib}.lean")) for d, _, names in os.walk(f"{tree}/{lib}"): files += [(lib, os.path.relpath(os.path.join(d, n), tree)) for n in names if n.endswith(".lean")] files.sort(key=lambda x: x[1]) def one(item): lib, f = item with tempfile.NamedTemporaryFile(suffix=".perf") as tmp: t = time.time() r = subprocess.run(["perf-bin", "stat", "-e", "instructions:u", "-x", ",", "-o", tmp.name, "--", lean, "-j1", "-DElab.async=false", *opts[lib], f], cwd=tree, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) n = next((int(l.split(",")[0]) for l in open(tmp.name) if "instructions" in l and l.split(",")[0].isdigit()), 0) return f[:-5].replace("/", "."), f, n, round(time.time() - t, 1), r.returncode start = time.time() with concurrent.futures.ThreadPoolExecutor(workers) as ex: rows = list(ex.map(one, files)) with open(out, "w") as f: for row in rows: f.write("\t".join(map(str, row)) + "\n") ok = [r for r in rows if r[4] == 0 and r[2]] print(f"{len(rows)} modules, total {sum(r[2] for r in ok):.4e} instructions:u over {len(ok)}; {len(rows) - len(ok)} did not elaborate alone: {[r[0] for r in rows if r not in ok][:6]}; {time.time() - start:.0f} s on {workers} workers")