benchmarks/measure_http.py
"""Warm, sequential loopback HTTP/1.1 requests; each opens a new TCP connection."""
import os
from pathlib import Path
import statistics
import subprocess
import sys
import tempfile
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from http_support import listening, exchange
VM = Path(os.getenv("BASALT", ROOT / "basalt")).resolve()
source = ROOT / "examples/http_server.bas"
request = b"GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n"
expected = (b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 3\r\n"
b"Connection: close\r\n\r\nok\n")
count = 1000
with tempfile.TemporaryDirectory() as folder:
work = Path(folder)
binary, reference = work / "server", work / "reference"
subprocess.run(["sh", ROOT / "build-native.sh", source, binary], check=True,
env=dict(os.environ, BASALT=str(VM)))
subprocess.run([os.getenv("CC", "cc"), "-std=c11", "-O3", "-I", ROOT / "src",
ROOT / "benchmarks/http_reference.c", "-o", reference], check=True)
cmds = {"VM": [VM, "run", source], "AOT": [binary], "C": [reference]}
samples = {mode: [] for mode in cmds}
order = list(cmds)
for trial in range(9):
for mode in order:
with listening(cmds[mode], folder) as port:
for i in range(40):
assert exchange(port, request) == expected
start = time.perf_counter()
for i in range(count):
if exchange(port, request) != expected:
raise RuntimeError("unexpected HTTP response")
samples[mode].append(count / (time.perf_counter()-start))
order = order[1:] + order[:1]
for mode, values in samples.items():
print(f"{mode}: median {statistics.median(values):.0f} requests/s, "
f"range {min(values):.0f}..{max(values):.0f} (9 x {count})")