basalt

benchmarks/desktop.py

"""Measure the previous public distribution against the unified x64 tool."""
import argparse, json, os, platform, shutil, statistics, subprocess, tempfile, time, zipfile
from pathlib import Path

parser=argparse.ArgumentParser()
parser.add_argument("old",type=Path)
parser.add_argument("new",type=Path)
parser.add_argument("report",type=Path)
args=parser.parse_args()
root=Path(__file__).resolve().parents[1]
tool=args.new.resolve()
samples={}
def command(cmd, expected=None):
    tic=time.perf_counter_ns()
    proc=subprocess.run(list(map(str,cmd)),capture_output=True,check=True)
    elapsed=(time.perf_counter_ns()-tic)/1e6
    if expected is not None and proc.stdout.strip()!=expected:
        raise ValueError((cmd,proc.stdout,expected))
    return elapsed
def compare(key, a, b, expected=None, cleanup=None):
    samples[key]={"before":[],"after":[]}
    for i in range(10):
        for name,cmd in ([("before",a),("after",b)] if i%2==0 else [("after",b),("before",a)]):
            value=command(cmd,expected)
            if cleanup:cleanup()
            if i:samples[key][name].append(value)
with tempfile.TemporaryDirectory() as directory:
    d=Path(directory)
    with zipfile.ZipFile(args.old) as z:z.extractall(d)
    oldroot=d/"basalt-lang"
    deployed=d/"new-basalt"
    shutil.copyfile(tool,deployed);deployed.chmod(0o755);tool=deployed
    old=oldroot/"basalt"
    old.chmod(0o755)
    cc=shutil.which("cc")
    # Same optimizer, host CPU and source for the two interpreted versions.
    command([cc,"-O3","-s",oldroot/"src/basalt.c","-ldl","-o",old])
    src=root/"desktop/demo.bas"
    out=d/"program"
    oldbuild=["sh",oldroot/"build-native.sh",src,out]
    os.environ["BASALT"]=str(old)
    compare("build",oldbuild,[tool,"build",src,out],cleanup=lambda:out.unlink())
    arg=20000000
    expected=str(arg*(arg-1)//2).encode()
    compare("sum_vm",[old,"run",src,arg],[tool,"run",src,arg],expected)
    command(oldbuild)
    ref=d/"previous";out.rename(ref)
    command([tool,"build",src,out])
    compare("sum_compiled",[ref,arg],[out,arg],expected)
    names=d/"symbols.bas"
    names.write_text("\n".join(f"LET variable_{n} = {n}" for n in range(4000))+"\nPRINT variable_3999\n")
    compare("names_vm",[old,"run",names],[tool,"run",names],b"3999")
report={"system":platform.platform(),"compiler":subprocess.check_output(["cc","--version"],text=True).splitlines()[0],
        "repeat":9,"sum_terms":arg,"samples_ms":samples}
args.report.write_text(json.dumps(report,indent=2)+"\n")
for key,values in samples.items():print(key,{n:round(statistics.median(v),3) for n,v in values.items()})