Download scripts/testing/performance_benchmark.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 7.12 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/testing/performance_benchmark.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/testing/performance_benchmark.py
-
curl -L -o performance_benchmark.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/testing/performance_benchmark.py
7.12 kB
| #!/usr/bin/env python3 | |
| """ | |
| Performance benchmarking script for YAZ Care Platform | |
| Tests various endpoints and measures response times, throughput, and resource usage | |
| """ | |
| import asyncio | |
| import time | |
| import statistics | |
| from typing import List, Dict, Any | |
| import httpx | |
| import json | |
| BASE_URL = "http://localhost:8000" | |
| class PerformanceBenchmark: | |
| def __init__(self, base_url: str = BASE_URL): | |
| self.base_url = base_url | |
| self.results = [] | |
| async def benchmark_endpoint( | |
| self, | |
| endpoint: str, | |
| method: str = "GET", | |
| num_requests: int = 100, | |
| concurrent: int = 10, | |
| payload: Dict = None | |
| ) -> Dict[str, Any]: | |
| """Benchmark a single endpoint""" | |
| print(f"\n{'='*60}") | |
| print(f"Benchmarking: {method} {endpoint}") | |
| print(f"Requests: {num_requests}, Concurrent: {concurrent}") | |
| print(f"{'='*60}") | |
| response_times = [] | |
| errors = 0 | |
| async with httpx.AsyncClient(timeout=30.0) as client: | |
| # Warmup | |
| for _ in range(5): | |
| try: | |
| await client.request(method, f"{self.base_url}{endpoint}", json=payload) | |
| except: | |
| pass | |
| # Actual benchmark | |
| start_time = time.time() | |
| # Create semaphore for concurrency control | |
| semaphore = asyncio.Semaphore(concurrent) | |
| async def make_request(): | |
| async with semaphore: | |
| req_start = time.time() | |
| try: | |
| response = await client.request( | |
| method, | |
| f"{self.base_url}{endpoint}", | |
| json=payload | |
| ) | |
| req_time = time.time() - req_start | |
| response_times.append(req_time) | |
| return response.status_code | |
| except Exception as e: | |
| nonlocal errors | |
| errors += 1 | |
| return None | |
| # Execute all requests | |
| tasks = [make_request() for _ in range(num_requests)] | |
| await asyncio.gather(*tasks) | |
| total_time = time.time() - start_time | |
| # Calculate statistics | |
| if response_times: | |
| stats = { | |
| "endpoint": endpoint, | |
| "method": method, | |
| "total_requests": num_requests, | |
| "concurrent_requests": concurrent, | |
| "successful_requests": len(response_times), | |
| "failed_requests": errors, | |
| "total_time": round(total_time, 3), | |
| "requests_per_second": round(num_requests / total_time, 2), | |
| "response_times": { | |
| "min": round(min(response_times) * 1000, 2), # ms | |
| "max": round(max(response_times) * 1000, 2), # ms | |
| "mean": round(statistics.mean(response_times) * 1000, 2), # ms | |
| "median": round(statistics.median(response_times) * 1000, 2), # ms | |
| "p95": round(statistics.quantiles(response_times, n=20)[18] * 1000, 2) if len(response_times) > 1 else 0, # ms | |
| "p99": round(statistics.quantiles(response_times, n=100)[98] * 1000, 2) if len(response_times) > 1 else 0, # ms | |
| } | |
| } | |
| else: | |
| stats = { | |
| "endpoint": endpoint, | |
| "method": method, | |
| "error": "All requests failed", | |
| "failed_requests": errors | |
| } | |
| # Print results | |
| if "response_times" in stats: | |
| print(f"✅ Success Rate: {stats['successful_requests']}/{stats['total_requests']}") | |
| print(f"⚡ Throughput: {stats['requests_per_second']} req/s") | |
| print(f"📊 Response Times (ms):") | |
| print(f" Min: {stats['response_times']['min']}") | |
| print(f" Median: {stats['response_times']['median']}") | |
| print(f" Mean: {stats['response_times']['mean']}") | |
| print(f" P95: {stats['response_times']['p95']}") | |
| print(f" P99: {stats['response_times']['p99']}") | |
| print(f" Max: {stats['response_times']['max']}") | |
| else: | |
| print(f"❌ {stats.get('error', 'Unknown error')}") | |
| self.results.append(stats) | |
| return stats | |
| async def run_full_benchmark(self): | |
| """Run comprehensive benchmark suite""" | |
| print("\n" + "="*60) | |
| print("YAZ CARE PLATFORM - PERFORMANCE BENCHMARK") | |
| print("="*60) | |
| # Core endpoints | |
| await self.benchmark_endpoint("/api/health", num_requests=200, concurrent=20) | |
| await self.benchmark_endpoint("/api/status", num_requests=200, concurrent=20) | |
| # Module health checks | |
| await self.benchmark_endpoint("/api/surgio/health", num_requests=100, concurrent=10) | |
| await self.benchmark_endpoint("/api/clinica/health", num_requests=100, concurrent=10) | |
| # UI pages (lower concurrency) | |
| await self.benchmark_endpoint("/", num_requests=50, concurrent=5) | |
| await self.benchmark_endpoint("/docs", num_requests=50, concurrent=5) | |
| # Metrics endpoint | |
| await self.benchmark_endpoint("/metrics", num_requests=100, concurrent=10) | |
| # Summary | |
| print("\n" + "="*60) | |
| print("BENCHMARK SUMMARY") | |
| print("="*60) | |
| total_requests = sum(r.get("total_requests", 0) for r in self.results) | |
| total_successful = sum(r.get("successful_requests", 0) for r in self.results) | |
| total_failed = sum(r.get("failed_requests", 0) for r in self.results) | |
| print(f"Total Requests: {total_requests}") | |
| print(f"Successful: {total_successful} ({total_successful/total_requests*100:.1f}%)") | |
| print(f"Failed: {total_failed} ({total_failed/total_requests*100:.1f}%)") | |
| # Best and worst performers | |
| api_results = [r for r in self.results if "response_times" in r and "/api/" in r["endpoint"]] | |
| if api_results: | |
| fastest = min(api_results, key=lambda x: x["response_times"]["median"]) | |
| slowest = max(api_results, key=lambda x: x["response_times"]["median"]) | |
| print(f"\n🏆 Fastest API: {fastest['endpoint']} ({fastest['response_times']['median']}ms median)") | |
| print(f"🐌 Slowest API: {slowest['endpoint']} ({slowest['response_times']['median']}ms median)") | |
| # Save results | |
| with open("/tmp/yaz_performance_benchmark.json", "w") as f: | |
| json.dump(self.results, f, indent=2) | |
| print(f"\n📄 Full results saved to: /tmp/yaz_performance_benchmark.json") | |
| return self.results | |
| async def main(): | |
| benchmark = PerformanceBenchmark() | |
| await benchmark.run_full_benchmark() | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |