#!/usr/bin/env python3 """Profile Q-063 through lower, check-AIR and check-source; never terminate a run by time.""" import argparse import hashlib import json from pathlib import Path import resource import statistics import subprocess import tempfile import time KINDS = ('scope', 'shield', 'while', 'loop', 'match', 'while_live', 'match_live') REPO = Path(__file__).resolve().parents[1] def source(kind, depth): leaf = 'let x: u8 = 1; ' live = kind.endswith('_live') if live: leaf = 'x = x + 1u64; ' if kind == 'scope': body = 'scope s { ' * depth + leaf + '} ' * depth elif kind == 'shield': body = 'shield { ' * depth + leaf + '} ' * depth elif kind in ('while', 'while_live'): body = 'while false { ' * depth + leaf + '} ' * depth elif kind == 'loop': body = 'loop { ' * depth + 'break; ' + '} break; ' * (depth - 1) + '} ' else: body = 'match 0u8 { 0 => { ' * depth + leaf + '} _ => {} } ' * depth return ('module probe\nfn main() -> u64 effects [] { ' + ('var x: u64 = 0u64; ' if live else '') + body + ('return x;' if live else 'return 0u64;') + ' }\n') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--aji', type=Path, default=REPO / 'zig-out/bin/aji') parser.add_argument('--out', type=Path, help='new directory for sources, AIR, records and provenance') parser.add_argument('--depths', type=int, nargs='+', default=[32, 64, 128, 256]) parser.add_argument('--kinds', choices=KINDS, nargs='+', default=list(KINDS)) parser.add_argument('--repeats', type=int, default=3) args = parser.parse_args() if args.repeats < 1 or any(d < 1 for d in args.depths): parser.error('depths and repeats must be positive') if args.out: root = args.out.resolve() root.mkdir(parents=True, exist_ok=False) else: root = Path(tempfile.mkdtemp(prefix='aji-control-profile-')) binary = args.aji.resolve() metadata = { 'head': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip(), 'binary': str(binary), 'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(), 'depths': args.depths, 'kinds': args.kinds, 'repeats': args.repeats, } (root / 'provenance.json').write_text(json.dumps(metadata, indent=2) + '\n') print(f'Artifacts: {root}', flush=True) summary = [] with (root / 'timings.jsonl').open('w') as log: for kind in args.kinds: for depth in args.depths: src = root / f'{kind}-{depth}.aji' src.write_text(source(kind, depth)) air = src.with_suffix('.air') for stage, command, path in [('lower', 'lower', src), ('verify_air', 'check', air), ('check', 'check', src)]: samples = [] for repeat in range(args.repeats): before = resource.getrusage(resource.RUSAGE_CHILDREN) started = time.perf_counter() result = subprocess.run([str(binary), command, str(path)], capture_output=True) elapsed = time.perf_counter() - started after = resource.getrusage(resource.RUSAGE_CHILDREN) row = dict(kind=kind, depth=depth, stage=stage, repeat=repeat, wall_s=elapsed, cpu_s=after.ru_utime + after.ru_stime - before.ru_utime - before.ru_stime, exit_code=result.returncode) log.write(json.dumps(row) + '\n') log.flush() if result.returncode or result.stderr or (stage != 'lower' and result.stdout): (root / 'failure.stdout').write_bytes(result.stdout) (root / 'failure.stderr').write_bytes(result.stderr) raise RuntimeError(f'{kind}/{depth}/{stage} did not accept cleanly: exit {result.returncode}') if stage == 'lower': if repeat and air.read_bytes() != result.stdout: raise RuntimeError('repeated lowering produced different AIR') air.write_bytes(result.stdout) samples.append(row) item = dict(kind=kind, depth=depth, stage=stage, median_s=statistics.median(r['wall_s'] for r in samples), median_cpu_s=statistics.median(r['cpu_s'] for r in samples)) summary.append(item) print(json.dumps(item), flush=True) (root / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') inputs = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(root.iterdir()) if p.suffix in ('.aji', '.air')} (root / 'inputs.sha256.json').write_text(json.dumps(inputs, indent=2) + '\n') (root / 'complete.json').write_text(json.dumps({'exit_code': 0, 'runs': len(summary) * args.repeats}) + '\n') if __name__ == '__main__': main()