File size: 7,118 Bytes
372384b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | #!/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())
|