4343import datetime
4444import json
4545import os
46+ import platform
4647import shutil
4748import socket
4849import statistics
4950import subprocess
5051import sys
52+ import tempfile
5153import time
5254from pathlib import Path
5355
@@ -634,6 +636,273 @@ def measure_pair(name: str, a_cmd: list[str], b_cmd: list[str], c_cmd: list[str]
634636 return out
635637
636638
639+ AOT_BENCHMARKS : dict [str , tuple [str , str , str | None ]] = {
640+ "empty" : ("empty.py" , "empty" , None ),
641+ "hello" : ("hello.py" , "hello" , None ),
642+ "nbody" : ("nbody.py" , "nbody" , "200000" ),
643+ "spectral-norm" : ("spectral_norm.py" , "spectral_norm" , "400" ),
644+ "fannkuch-redux" : ("fannkuch.py" , "fannkuch" , "9" ),
645+ }
646+ AOT_SHARED_RUNNER_NOTE = "Recorded on a shared runner; compare ratios, not absolute times."
647+
648+
649+ def normalize_ru_maxrss (raw_maxrss : int , system : str | None = None ) -> int :
650+ """Convert getrusage/wait4 ru_maxrss to bytes (macOS reports bytes; Linux reports KiB)."""
651+ sys_name = system if system is not None else platform .system ()
652+ if sys_name == "Darwin" :
653+ return int (raw_maxrss )
654+ return int (raw_maxrss ) * 1024
655+
656+
657+ def read_cpu_model (cpuinfo_path : Path | None = None ) -> str :
658+ """Return the CPU model string from /proc/cpuinfo on Linux, or platform.processor()."""
659+ path = cpuinfo_path if cpuinfo_path is not None else Path ("/proc/cpuinfo" )
660+ try :
661+ if path .is_file ():
662+ for line in path .read_text (errors = "replace" ).splitlines ():
663+ if line .lower ().startswith ("model name" ) and ":" in line :
664+ model = line .split (":" , 1 )[1 ].strip ()
665+ if model :
666+ return model
667+ except OSError :
668+ pass
669+ return platform .processor () or platform .machine () or "unknown"
670+
671+
672+ def _cmd_version (cmd : list [str ]) -> str :
673+ try :
674+ r = subprocess .run (cmd , capture_output = True , text = True )
675+ out = (r .stdout .strip () or r .stderr .strip ()).splitlines ()
676+ return out [0 ] if out else "unknown"
677+ except OSError :
678+ return "unknown"
679+
680+
681+ def collect_aot_metadata (python : str , rustc : str | None = None ) -> dict [str , str ]:
682+ """Collect runner, toolchain, and commit metadata for an aot-measure run."""
683+ try :
684+ commit = subprocess .run (
685+ ["git" , "rev-parse" , "HEAD" ], cwd = ROOT , capture_output = True , text = True
686+ ).stdout .strip () or "unknown"
687+ except OSError :
688+ commit = "unknown"
689+ runner_image = f"{ os .environ .get ('ImageOS' , platform .system ())} { os .environ .get ('ImageVersion' , platform .release ())} " .strip ()
690+ rustc_bin = rustc or shutil .which ("rustc" ) or "rustc"
691+ return {
692+ "commit" : commit ,
693+ "runner_image" : runner_image ,
694+ "cpu_model" : read_cpu_model (),
695+ "python" : _cmd_version ([python , "--version" ]),
696+ "rustc" : _cmd_version ([rustc_bin , "--version" ]),
697+ "shared_runner_note" : AOT_SHARED_RUNNER_NOTE ,
698+ }
699+
700+
701+ def binary_sizes (path : Path ) -> tuple [int , int ]:
702+ """Return (unstripped_bytes, stripped_bytes) without modifying the original binary."""
703+ unstripped = path .stat ().st_size
704+ strip_bin = shutil .which ("strip" )
705+ if not strip_bin :
706+ return unstripped , unstripped
707+ stripped_path = Path (f"{ path } .stripped" )
708+ shutil .copy2 (path , stripped_path )
709+ result = subprocess .run ([strip_bin , str (stripped_path )], capture_output = True , text = True )
710+ if result .returncode != 0 :
711+ return unstripped , unstripped
712+ return unstripped , stripped_path .stat ().st_size
713+
714+
715+ def run_once_with_usage (cmd : list [str ], env : dict [str , str ] | None = None ) -> dict [str , object ]:
716+ """Run one child process and return wall time, CPU time, peak RSS (bytes), exit code, and stdout."""
717+ with tempfile .TemporaryFile () as out_f , tempfile .TemporaryFile () as err_f :
718+ start = time .perf_counter ()
719+ if hasattr (os , "wait4" ):
720+ proc = subprocess .Popen (cmd , stdout = out_f , stderr = err_f , env = env )
721+ _ , status , rusage = os .wait4 (proc .pid , 0 )
722+ elapsed = time .perf_counter () - start
723+ returncode = os .waitstatus_to_exitcode (status )
724+ proc .returncode = returncode
725+ cpu_s = float (rusage .ru_utime ) + float (rusage .ru_stime )
726+ max_rss_bytes = normalize_ru_maxrss (int (rusage .ru_maxrss ))
727+ else :
728+ res = subprocess .run (cmd , stdout = out_f , stderr = err_f , env = env )
729+ elapsed = time .perf_counter () - start
730+ returncode = res .returncode
731+ cpu_s = elapsed
732+ max_rss_bytes = 0
733+ out_f .seek (0 )
734+ err_f .seek (0 )
735+ stdout = out_f .read ().decode ("utf-8" , errors = "replace" ).strip ()
736+ stderr = err_f .read ().decode ("utf-8" , errors = "replace" ).strip ()
737+ return {
738+ "wall_s" : elapsed ,
739+ "cpu_s" : cpu_s ,
740+ "max_rss_bytes" : max_rss_bytes ,
741+ "returncode" : returncode ,
742+ "stdout" : stdout ,
743+ "stderr" : stderr ,
744+ }
745+
746+
747+ def compute_aot_ratios (aot : dict [str , object ], rust : dict [str , object ]) -> dict [str , float | None ]:
748+ """Compute aot / rust ratios for stripped_bytes, max_rss_bytes, cpu_s, and wall_s."""
749+ ratios : dict [str , float | None ] = {}
750+ for key in ("stripped_bytes" , "max_rss_bytes" , "cpu_s" , "wall_s" ):
751+ a_val = aot .get (key )
752+ r_val = rust .get (key )
753+ if isinstance (a_val , (int , float )) and isinstance (r_val , (int , float )) and r_val > 0 :
754+ ratios [key ] = float (a_val ) / float (r_val )
755+ else :
756+ ratios [key ] = None
757+ return ratios
758+
759+
760+ def _fmt_bytes (n : object ) -> str :
761+ if not isinstance (n , (int , float )):
762+ return "n/a"
763+ if n >= 1024 * 1024 :
764+ return f"{ n / (1024 * 1024 ):.2f} MiB"
765+ if n >= 1024 :
766+ return f"{ n / 1024 :.1f} KiB"
767+ return f"{ int (n )} B"
768+
769+
770+ def _fmt_ratio (v : object ) -> str :
771+ if not isinstance (v , (int , float )):
772+ return "n/a"
773+ return f"{ v :.2f} x"
774+
775+
776+ def _fmt_secs (v : object ) -> str :
777+ if not isinstance (v , (int , float )):
778+ return "n/a"
779+ return f"{ v :.4f} s"
780+
781+
782+ def format_aot_report (metadata : dict [str , str ], results : dict [str , dict [str , object ]]) -> str :
783+ """Format the aot-measure metadata header and Markdown summary table."""
784+ lines = [
785+ f"commit: { metadata .get ('commit' , 'unknown' )} " ,
786+ f"runner_image: { metadata .get ('runner_image' , 'unknown' )} " ,
787+ f"cpu_model: { metadata .get ('cpu_model' , 'unknown' )} " ,
788+ f"python: { metadata .get ('python' , 'unknown' )} " ,
789+ f"rustc: { metadata .get ('rustc' , 'unknown' )} " ,
790+ f"note: { metadata .get ('shared_runner_note' , AOT_SHARED_RUNNER_NOTE )} " ,
791+ "" ,
792+ "| benchmark | size | AOT stripped | Rust stripped | size ratio | AOT RSS | Rust RSS | CPython RSS | RSS ratio | AOT CPU | Rust CPU | CPU ratio |" ,
793+ "|---|---|---|---|---|---|---|---|---|---|---|---|" ,
794+ ]
795+ for name , entry in results .items ():
796+ size = entry .get ("size" ) or "-"
797+ aot = entry ["TypedPython AOT" ] # type: ignore[index]
798+ rust = entry ["Rust" ] # type: ignore[index]
799+ cpy = entry ["CPython" ] # type: ignore[index]
800+ ratios = entry ["ratios_vs_rust" ] # type: ignore[index]
801+ lines .append (
802+ f"| { name } | { size } | { _fmt_bytes (aot ['stripped_bytes' ])} | { _fmt_bytes (rust ['stripped_bytes' ])} | " # type: ignore[index]
803+ f"{ _fmt_ratio (ratios ['stripped_bytes' ])} | { _fmt_bytes (aot ['max_rss_bytes' ])} | " # type: ignore[index]
804+ f"{ _fmt_bytes (rust ['max_rss_bytes' ])} | { _fmt_bytes (cpy ['max_rss_bytes' ])} | " # type: ignore[index]
805+ f"{ _fmt_ratio (ratios ['max_rss_bytes' ])} | { _fmt_secs (aot ['cpu_s' ])} | " # type: ignore[index]
806+ f"{ _fmt_secs (rust ['cpu_s' ])} | { _fmt_ratio (ratios ['cpu_s' ])} |" # type: ignore[index]
807+ )
808+ return "\n " .join (lines )
809+
810+
811+ def aot_measure (args : argparse .Namespace ) -> int :
812+ """Build and measure CPython, Rust, and TypedPython AOT across baseline + Tier-K programs."""
813+ if not args .typedpython :
814+ sys .stderr .write ("aot-measure requires --typedpython <dir>\n " )
815+ return 1
816+ cargo_bin = os .environ .get ("CARGO" ) or shutil .which ("cargo" ) or CARGO
817+ rust_bins = [rs for _ , rs , _ in AOT_BENCHMARKS .values ()]
818+ rust_cmd = [cargo_bin , "build" , "--release" , "--quiet" ]
819+ for b in rust_bins :
820+ rust_cmd .extend (["--bin" , b ])
821+ run_checked (rust_cmd , cwd = ROOT / "rust" , env = dict (os .environ , CARGO_TARGET_DIR = str (TARGET )))
822+
823+ aot_dir = TP_BUILD / "aot"
824+ aot_dir .mkdir (parents = True , exist_ok = True )
825+ tp_env = dict (os .environ , PYTHONPATH = str (Path (args .typedpython ).resolve ()))
826+ aot_exes : dict [str , Path ] = {}
827+ for name , (py , _ , _ ) in AOT_BENCHMARKS .items ():
828+ out_exe = aot_dir / name
829+ run_checked (
830+ [args .typedpython_python , "-m" , "typedpython" , "aot-build" , str (ROOT / "py" / py ), "-o" , str (out_exe )],
831+ env = tp_env ,
832+ )
833+ aot_exes [name ] = out_exe
834+
835+ metadata = collect_aot_metadata (args .python )
836+ results : dict [str , dict [str , object ]] = {}
837+ mismatch = False
838+
839+ for name , (py , rs , default_size ) in AOT_BENCHMARKS .items ():
840+ size = args .size .get (name , default_size )
841+ argv = [size ] if size is not None else []
842+ rust_exe = TARGET / "release" / rs
843+ aot_exe = aot_exes [name ]
844+ rust_unstripped , rust_stripped = binary_sizes (rust_exe )
845+ aot_unstripped , aot_stripped = binary_sizes (aot_exe )
846+
847+ cmds = {
848+ "CPython" : [args .python , str (ROOT / "py" / py ), * argv ],
849+ "Rust" : [str (rust_exe ), * argv ],
850+ "TypedPython AOT" : [str (aot_exe ), * argv ],
851+ }
852+ sizes_map : dict [str , tuple [int | None , int | None ]] = {
853+ "CPython" : (None , None ),
854+ "Rust" : (rust_unstripped , rust_stripped ),
855+ "TypedPython AOT" : (aot_unstripped , aot_stripped ),
856+ }
857+
858+ prog_res : dict [str , object ] = {"size" : size }
859+ outputs : dict [str , str ] = {}
860+ for col , cmd in cmds .items ():
861+ runs = []
862+ for _ in range (args .repeat ):
863+ r = run_once_with_usage (cmd )
864+ if r ["returncode" ] != 0 :
865+ sys .stderr .write (
866+ f"{ name } /{ col } : exited with { r ['returncode' ]} \n { r ['stderr' ]} \n "
867+ )
868+ return 1
869+ runs .append (r )
870+ out_set = {r ["stdout" ] for r in runs }
871+ if len (out_set ) != 1 :
872+ sys .stderr .write (f"{ name } /{ col } : non-deterministic output across repeats: { out_set !r} \n " )
873+ return 1
874+ out_str = str (runs [0 ]["stdout" ])
875+ outputs [col ] = out_str
876+ unstripped , stripped = sizes_map [col ]
877+ prog_res [col ] = {
878+ "wall_s" : statistics .median (float (r ["wall_s" ]) for r in runs ), # type: ignore[arg-type]
879+ "cpu_s" : statistics .median (float (r ["cpu_s" ]) for r in runs ), # type: ignore[arg-type]
880+ "max_rss_bytes" : int (statistics .median (int (r ["max_rss_bytes" ]) for r in runs )), # type: ignore[arg-type]
881+ "unstripped_bytes" : unstripped ,
882+ "stripped_bytes" : stripped ,
883+ "output" : out_str ,
884+ }
885+
886+ if len (set (outputs .values ())) != 1 :
887+ sys .stderr .write (f"{ name } : OUTPUTS DIFFER: { outputs !r} \n " )
888+ mismatch = True
889+ prog_res ["ratios_vs_rust" ] = compute_aot_ratios (
890+ prog_res ["TypedPython AOT" ], # type: ignore[arg-type]
891+ prog_res ["Rust" ], # type: ignore[arg-type]
892+ )
893+ results [name ] = prog_res
894+
895+ print (format_aot_report (metadata , results ))
896+ if args .out :
897+ out_path = Path (args .out )
898+ out_path .parent .mkdir (parents = True , exist_ok = True )
899+ out_path .write_text (
900+ json .dumps ({"metadata" : metadata , "repeat" : args .repeat , "results" : results }, indent = 2 ) + "\n "
901+ )
902+ print (f"wrote { out_path } " )
903+ return 1 if mismatch else 0
904+
905+
637906def main () -> int :
638907 parser = argparse .ArgumentParser (description = __doc__ , formatter_class = argparse .RawDescriptionHelpFormatter )
639908 sub = parser .add_subparsers (dest = "cmd" , required = True )
@@ -659,9 +928,21 @@ def main() -> int:
659928 m .add_argument ("--write" , action = "store_true" )
660929 m .add_argument ("--size" , action = "append" , default = [], metavar = "NAME=N" ,
661930 help = "override a benchmark size (for runner smoke tests only)" )
931+ aot = sub .add_parser ("aot-measure" , help = "measure CPython, Rust, and TypedPython AOT (size, RSS, CPU)" )
932+ aot .add_argument ("--python" , default = sys .executable )
933+ aot .add_argument ("--typedpython" , metavar = "DIR" , required = True ,
934+ help = "directory holding the typedpython package" )
935+ aot .add_argument ("--typedpython-python" , default = sys .executable ,
936+ help = "interpreter for running typedpython aot-build" )
937+ aot .add_argument ("--repeat" , type = int , default = 3 )
938+ aot .add_argument ("--size" , action = "append" , default = [], metavar = "NAME=N" ,
939+ help = "override a benchmark size" )
940+ aot .add_argument ("--out" , metavar = "PATH" , help = "write full JSON report to PATH" )
662941 args = parser .parse_args ()
663- if args .cmd in ("measure" , "interleaved" ):
942+ if args .cmd in ("measure" , "interleaved" , "aot-measure" ):
664943 args .size = dict (s .split ("=" , 1 ) for s in args .size )
944+ if args .cmd == "aot-measure" :
945+ return aot_measure (args )
665946 if args .cmd == "interleaved" :
666947 return interleaved (args )
667948 return verify (args ) if args .cmd == "verify" else measure (args )
0 commit comments