example/example_7.pyPython94 lines
example_7.py
Callback benchmarks, benchmark suites, statistics, exports and history
example/example_7.py
Pythonimport asyncio
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
import storq
from storq.benchmarking import (
BenchmarkHistory,
BenchmarkSuite,
WorkloadManager,
compare_benchmarks,
create_workload,
export_csv,
export_json,
latency_stats,
percentile,
)
def main() -> None:
with TemporaryDirectory() as directory:
output = Path(directory)
database = output / "bench.sqlite"
with closing(sqlite3.connect(database)) as connection:
connection.execute("CREATE TABLE sample (id INTEGER PRIMARY KEY)")
connection.execute("INSERT INTO sample DEFAULT VALUES")
def read_one() -> None:
with closing(sqlite3.connect(database)) as connection:
connection.execute("SELECT COUNT(*) FROM sample").fetchone()
registered = create_workload("single-row-read", read_one, category="read")
workloads = WorkloadManager()
workloads.register(registered)
print("Registered workload:", workloads.get("single-row-read").category)
async def run_benchmarks():
benchmark = storq.Benchmark(
"sqlite-read",
str(database),
profile="read",
)
baseline = await benchmark.run(
iterations=2,
warmup=1,
operation_count=4,
concurrency=2,
operation=read_one,
)
current = await benchmark.run(
iterations=2,
warmup=1,
operation_count=4,
concurrency=2,
operation=read_one,
)
print("Benchmark status:", baseline.status)
print("Latency summary:", baseline.aggregate["latency_ns"])
print(
"p95 latency (ns):",
percentile(baseline.measurements[0].operation_latencies_ns, 95),
)
print(
"Sample stats:",
latency_stats(baseline.measurements[0].operation_latencies_ns),
)
print(
"Comparable:",
compare_benchmarks(baseline, current).comparable,
)
suite = BenchmarkSuite("SQLite targets")
suite.add_database("sqlite", str(database))
suite_results = await suite.run(
profile="read",
iterations=1,
operation=read_one,
)
print("Suite status:", suite_results[0].status)
export_json(baseline, output / "benchmark.json")
export_csv(baseline, output / "benchmark.csv")
history = BenchmarkHistory(output / "benchmark-history")
history.add(baseline)
print("History entries:", len(history.list(status="completed")))
asyncio.run(run_benchmarks())
if __name__ == "__main__":
main()
