|
| 1 | +"""Core benchmark framework for FastPubSub performance measurement. |
| 2 | +
|
| 3 | +This module provides the infrastructure to measure Events Per Second (EPS) |
| 4 | +for different test cases, comparing FastPubSub performance against baseline. |
| 5 | +
|
| 6 | +Usage: |
| 7 | + python -m benchmarks.bench --case basic --duration 60 |
| 8 | + python -m benchmarks.bench --case raw_pubsub --duration 60 |
| 9 | + python -m benchmarks.bench --all --duration 60 |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import asyncio |
| 14 | +import csv |
| 15 | +import platform |
| 16 | +import sys |
| 17 | +import time |
| 18 | +from collections.abc import AsyncGenerator |
| 19 | +from contextlib import AbstractAsyncContextManager |
| 20 | +from dataclasses import dataclass |
| 21 | +from datetime import UTC, datetime |
| 22 | +from pathlib import Path |
| 23 | +from typing import Any, Protocol |
| 24 | + |
| 25 | +import psutil |
| 26 | + |
| 27 | +from fastpubsub.__about__ import __version__ |
| 28 | + |
| 29 | + |
| 30 | +class BenchmarkCase(Protocol): |
| 31 | + """Protocol defining the interface for all benchmark test cases. |
| 32 | +
|
| 33 | + All benchmark cases must implement: |
| 34 | + - EVENTS_PROCESSED: Counter for processed messages |
| 35 | + - case_name: Identifier for the test case |
| 36 | + - description: Human-readable description |
| 37 | + - start(): Async context manager that runs the benchmark |
| 38 | + """ |
| 39 | + |
| 40 | + EVENTS_PROCESSED: int |
| 41 | + case_name: str |
| 42 | + description: str |
| 43 | + |
| 44 | + def start(self) -> AbstractAsyncContextManager[float]: |
| 45 | + """Start the benchmark and yield the start time. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + Async context manager yielding the start timestamp. |
| 49 | + """ |
| 50 | + ... |
| 51 | + |
| 52 | + |
| 53 | +@dataclass |
| 54 | +class MeasureResult: |
| 55 | + """Container for benchmark measurement results. |
| 56 | +
|
| 57 | + Attributes: |
| 58 | + total_events: Total number of events processed. |
| 59 | + elapsed_time: Time elapsed in seconds. |
| 60 | + """ |
| 61 | + |
| 62 | + total_events: int |
| 63 | + elapsed_time: float |
| 64 | + |
| 65 | + @property |
| 66 | + def eps(self) -> float: |
| 67 | + """Calculate Events Per Second. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + float: Events per second (total_events / elapsed_time). |
| 71 | + """ |
| 72 | + if self.elapsed_time == 0: |
| 73 | + return 0.0 |
| 74 | + return self.total_events / self.elapsed_time |
| 75 | + |
| 76 | + |
| 77 | +async def measure(case: BenchmarkCase, measure_time: int) -> AsyncGenerator[MeasureResult, None]: |
| 78 | + """Run benchmark and yield results every second. |
| 79 | +
|
| 80 | + Args: |
| 81 | + case: The benchmark case to run. |
| 82 | + measure_time: Duration to run the benchmark in seconds. |
| 83 | +
|
| 84 | + Yields: |
| 85 | + MeasureResult: Current measurement snapshot every second. |
| 86 | + """ |
| 87 | + async with case.start() as start_time: |
| 88 | + while (elapsed_time := (time.time() - start_time)) < measure_time: |
| 89 | + yield MeasureResult(case.EVENTS_PROCESSED, elapsed_time) |
| 90 | + await asyncio.sleep(1.0) |
| 91 | + |
| 92 | + yield MeasureResult(case.EVENTS_PROCESSED, time.time() - start_time) |
| 93 | + |
| 94 | + |
| 95 | +async def run_benchmark(case: BenchmarkCase, measure_time: int) -> MeasureResult: |
| 96 | + """Execute a benchmark with real-time progress display. |
| 97 | +
|
| 98 | + Args: |
| 99 | + case: The benchmark case to run. |
| 100 | + measure_time: Duration to run the benchmark in seconds. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + MeasureResult: Final measurement results. |
| 104 | + """ |
| 105 | + result = MeasureResult(0, 0.0) |
| 106 | + |
| 107 | + async for result in measure(case, measure_time): |
| 108 | + # Clear line and print progress |
| 109 | + sys.stdout.write( |
| 110 | + f"\r[{case.case_name}] Events: {result.total_events:,}, " |
| 111 | + f"Time: {result.elapsed_time:.1f}s ({(measure_time - result.elapsed_time):.1f}s left), " |
| 112 | + f"EPS: {result.eps:,.2f} " |
| 113 | + ) |
| 114 | + sys.stdout.flush() |
| 115 | + |
| 116 | + # Print newline after progress |
| 117 | + print() |
| 118 | + return result |
| 119 | + |
| 120 | + |
| 121 | +def save_results( |
| 122 | + case: BenchmarkCase, |
| 123 | + result: MeasureResult, |
| 124 | + results_file: Path, |
| 125 | +) -> None: |
| 126 | + """Save benchmark results to CSV file. |
| 127 | +
|
| 128 | + Args: |
| 129 | + case: The benchmark case that was run. |
| 130 | + result: The measurement results. |
| 131 | + results_file: Path to the CSV file. |
| 132 | + """ |
| 133 | + file_exists = results_file.exists() |
| 134 | + mem = psutil.virtual_memory() |
| 135 | + |
| 136 | + with results_file.open("a", newline="") as csvfile: |
| 137 | + writer = csv.writer(csvfile, delimiter=";") |
| 138 | + |
| 139 | + # Write header if file is new |
| 140 | + if not file_exists: |
| 141 | + writer.writerow( |
| 142 | + [ |
| 143 | + "FastPubSub Version", |
| 144 | + "Case", |
| 145 | + "Total Events", |
| 146 | + "Elapsed Time", |
| 147 | + "EPS", |
| 148 | + "Timestamp", |
| 149 | + "Python Version", |
| 150 | + "Description", |
| 151 | + "Host Memory", |
| 152 | + ] |
| 153 | + ) |
| 154 | + |
| 155 | + writer.writerow( |
| 156 | + [ |
| 157 | + __version__, |
| 158 | + case.case_name, |
| 159 | + result.total_events, |
| 160 | + f"{result.elapsed_time:.2f}", |
| 161 | + f"{result.eps:.2f}", |
| 162 | + datetime.now(tz=UTC).isoformat(), |
| 163 | + platform.python_version(), |
| 164 | + case.description, |
| 165 | + f"{mem.total / (1024**3):.2f} GB", |
| 166 | + ] |
| 167 | + ) |
| 168 | + |
| 169 | + |
| 170 | +def print_results(cases_results: list[tuple[BenchmarkCase, MeasureResult]]) -> None: |
| 171 | + """Print formatted benchmark results table. |
| 172 | +
|
| 173 | + Args: |
| 174 | + cases_results: List of (case, result) tuples. |
| 175 | + """ |
| 176 | + print("\n" + "=" * 60) |
| 177 | + print("BENCHMARK RESULTS") |
| 178 | + print("=" * 60) |
| 179 | + print(f"{'Case':<15} | {'Events':>12} | {'EPS':>12} | Description") |
| 180 | + print("-" * 60) |
| 181 | + |
| 182 | + for case, result in cases_results: |
| 183 | + print( |
| 184 | + f"{case.case_name:<15} | {result.total_events:>12,} | " |
| 185 | + f"{result.eps:>12,.2f} | {case.description}" |
| 186 | + ) |
| 187 | + |
| 188 | + print("-" * 60) |
| 189 | + |
| 190 | + # Calculate overhead if we have both cases |
| 191 | + if len(cases_results) == 2: |
| 192 | + raw_result = next((r for c, r in cases_results if c.case_name == "raw_pubsub"), None) |
| 193 | + basic_result = next((r for c, r in cases_results if c.case_name == "basic"), None) |
| 194 | + |
| 195 | + if raw_result and basic_result and raw_result.eps > 0: |
| 196 | + overhead = ((raw_result.eps - basic_result.eps) / raw_result.eps) * 100 |
| 197 | + print(f"FastPubSub overhead: {overhead:.1f}%") |
| 198 | + print("=" * 60) |
| 199 | + |
| 200 | + |
| 201 | +async def main() -> None: |
| 202 | + """Main entry point for the benchmark CLI.""" |
| 203 | + parser = argparse.ArgumentParser( |
| 204 | + description="FastPubSub Benchmark Suite", |
| 205 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 206 | + epilog=""" |
| 207 | +Examples: |
| 208 | + python -m benchmarks.bench --case basic --duration 60 |
| 209 | + python -m benchmarks.bench --case raw_pubsub --duration 60 |
| 210 | + python -m benchmarks.bench --all --duration 60 |
| 211 | + """, |
| 212 | + ) |
| 213 | + parser.add_argument( |
| 214 | + "--case", |
| 215 | + choices=["basic", "raw_pubsub"], |
| 216 | + default="basic", |
| 217 | + help="Benchmark case to run (default: basic)", |
| 218 | + ) |
| 219 | + parser.add_argument( |
| 220 | + "--duration", |
| 221 | + type=int, |
| 222 | + default=60, |
| 223 | + help="Duration in seconds (default: 60)", |
| 224 | + ) |
| 225 | + parser.add_argument( |
| 226 | + "--all", |
| 227 | + action="store_true", |
| 228 | + help="Run all benchmark cases", |
| 229 | + ) |
| 230 | + |
| 231 | + args = parser.parse_args() |
| 232 | + |
| 233 | + # Import cases here to avoid circular imports |
| 234 | + from benchmarks.cases.basic import BasicTestCase |
| 235 | + from benchmarks.cases.raw_pubsub import RawPubSubTestCase |
| 236 | + |
| 237 | + results_file = Path(__file__).resolve().parent / "results" / "benches.csv" |
| 238 | + cases_results: list[tuple[Any, MeasureResult]] = [] |
| 239 | + |
| 240 | + cases: list[Any] |
| 241 | + if args.all: |
| 242 | + cases = [RawPubSubTestCase(), BasicTestCase()] |
| 243 | + elif args.case == "basic": |
| 244 | + cases = [BasicTestCase()] |
| 245 | + else: |
| 246 | + cases = [RawPubSubTestCase()] |
| 247 | + |
| 248 | + print(f"\nFastPubSub Benchmark Suite v{__version__}") |
| 249 | + print(f"Duration: {args.duration}s per case") |
| 250 | + print(f"Python: {platform.python_version()}") |
| 251 | + print("-" * 60) |
| 252 | + |
| 253 | + for case in cases: |
| 254 | + print(f"\nStarting benchmark: {case.case_name}") |
| 255 | + print(f"Description: {case.description}") |
| 256 | + print() |
| 257 | + |
| 258 | + result = await run_benchmark(case, args.duration) |
| 259 | + cases_results.append((case, result)) |
| 260 | + |
| 261 | + # Save results immediately after each case |
| 262 | + save_results(case, result, results_file) |
| 263 | + |
| 264 | + # Print summary table |
| 265 | + print_results(cases_results) |
| 266 | + print(f"\nResults saved to: {results_file}") |
| 267 | + |
| 268 | + |
| 269 | +if __name__ == "__main__": |
| 270 | + asyncio.run(main()) |
0 commit comments