Files
langchain4j-demo/quarkus-vs-spring-ai/scripts/bench.py
T

100 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""
Startup / memory / latency harness. Runs every app RUNS times against the stub LLM, interleaved
(quarkus, spring, quarkus, spring, ...) so both see the same background load.
RUNS=7 python3 scripts/bench.py # needs the stub on :18089 (scripts/start-stub.sh)
Measured per run:
t_port ms from process launch until the app's TCP port accepts a connection
t_first ms from process launch until GET /ask?q=... returns 200 (first answered request)
cpu_first CPU milliseconds (user+sys, from /proc) consumed by then; far less sensitive to a busy host than wall time
rss_first RSS in MiB right after that first answer
rss_after RSS in MiB after 300 further requests (a mix of tool, RAG and plain questions)
p50 / p95 latency in ms over those 300 sequential requests
The model is a local stub, so these numbers are framework overhead and nothing else.
"""
import os, socket, statistics, subprocess, sys, time, urllib.parse, urllib.request
RUNS = int(os.environ.get("RUNS", "5"))
PORT = int(os.environ.get("APP_PORT", "18080"))
STUB = "http://localhost:18089/v1"
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
QUESTIONS = ["Where is my order 1001?", "How many days do I have to return an item?", "What is the weather in Paris"]
APPS = {
"quarkus-jvm": ["java", f"-Dquarkus.http.port={PORT}", f"-Dquarkus.langchain4j.openai.base-url={STUB}",
"-jar", f"{ROOT}/quarkus-app/target/quarkus-app/quarkus-run.jar"],
"spring-jvm": ["java", f"-Dserver.port={PORT}", f"-Dspring.ai.openai.base-url={STUB}",
"-jar", f"{ROOT}/spring-ai-app/target/spring-ai-app-1.0.0.jar"],
}
NATIVE = f"{ROOT}/quarkus-app/target/quarkus-app-1.0.0-runner"
if os.path.exists(NATIVE):
APPS["quarkus-native"] = [NATIVE, f"-Dquarkus.http.port={PORT}", f"-Dquarkus.langchain4j.openai.base-url={STUB}"]
if os.environ.get("ONLY"):
APPS = {k: v for k, v in APPS.items() if k in os.environ["ONLY"].split(",")}
def rss_mib(pid):
for line in open(f"/proc/{pid}/status"):
if line.startswith("VmRSS"):
return int(line.split()[1]) / 1024
def cpu_ms(pid):
f = open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()
return (int(f[11]) + int(f[12])) * 1000 / os.sysconf("SC_CLK_TCK")
def ask(q):
with urllib.request.urlopen(f"http://localhost:{PORT}/ask?q=" + urllib.parse.quote(q), timeout=10) as r:
assert r.status == 200
return r.read()
def one_run(cmd):
t0 = time.perf_counter()
p = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
try:
while True:
try:
socket.create_connection(("localhost", PORT), timeout=0.05).close()
t_port = (time.perf_counter() - t0) * 1000
break
except OSError:
time.sleep(0.005)
if time.perf_counter() - t0 > 90:
raise SystemExit("app did not start")
while True:
try:
ask(QUESTIONS[0]); break
except Exception:
time.sleep(0.005)
t_first = (time.perf_counter() - t0) * 1000
rss_first, cpu_first = rss_mib(p.pid), cpu_ms(p.pid)
lat = []
for i in range(300):
s = time.perf_counter()
ask(QUESTIONS[i % 3])
lat.append((time.perf_counter() - s) * 1000)
lat.sort()
return dict(t_port=t_port, t_first=t_first, cpu_first=cpu_first, rss_first=rss_first,
rss_after=rss_mib(p.pid), p50=lat[149], p95=lat[284])
finally:
p.kill(); p.wait()
time.sleep(1.0)
def main():
print(f"host: {os.cpu_count()} cpus, load average at start {os.getloadavg()[0]:.1f} (other processes were running)")
rows = {name: [] for name in APPS}
for _ in range(RUNS):
for name, cmd in APPS.items():
rows[name].append(one_run(cmd))
for name, rs in rows.items():
print(f"\n== {name} ({RUNS} runs)")
print(f"{'metric':10s} " + " ".join(f"{'run'+str(i+1):>7s}" for i in range(RUNS)) + f" {'median':>8s}")
for k in ["t_port", "t_first", "cpu_first", "rss_first", "rss_after", "p50", "p95"]:
vals = [r[k] for r in rs]
fmt = "{:7.1f}" if k in ("rss_first", "rss_after", "p50", "p95") else "{:7.0f}"
print(f"{k:10s} " + " ".join(fmt.format(v) for v in vals) + " " + fmt.format(statistics.median(vals)).rjust(8))
print(f"\nload average at end {os.getloadavg()[0]:.1f}")
main()