Monitor system resources and performance during load tests.
| 40 | |
| 41 | |
| 42 | class LoadTestMonitor: |
| 43 | """Monitor system resources and performance during load tests.""" |
| 44 | |
| 45 | def __init__(self): |
| 46 | self.monitoring = False |
| 47 | self.metrics = { |
| 48 | "response_times": [], |
| 49 | "error_counts": [], |
| 50 | "queue_depths": [], |
| 51 | "memory_usage": [], |
| 52 | "cpu_usage": [], |
| 53 | "connection_counts": [], |
| 54 | "message_loss": 0 |
| 55 | } |
| 56 | |
| 57 | async def start_monitoring(self): |
| 58 | """Start continuous monitoring.""" |
| 59 | self.monitoring = True |
| 60 | |
| 61 | async def monitor_loop(): |
| 62 | while self.monitoring: |
| 63 | # Record system metrics |
| 64 | process = psutil.Process() |
| 65 | |
| 66 | self.metrics["memory_usage"].append({ |
| 67 | "timestamp": time.perf_counter(), |
| 68 | "memory_mb": process.memory_info().rss / 1024 / 1024, |
| 69 | "memory_percent": process.memory_percent() |
| 70 | }) |
| 71 | |
| 72 | self.metrics["cpu_usage"].append({ |
| 73 | "timestamp": time.perf_counter(), |
| 74 | "cpu_percent": process.cpu_percent(interval=None) |
| 75 | }) |
| 76 | |
| 77 | await asyncio.sleep(1.0) # Monitor every second |
| 78 | |
| 79 | self.monitor_task = asyncio.create_task(monitor_loop()) |
| 80 | |
| 81 | def stop_monitoring(self): |
| 82 | """Stop monitoring and return final metrics.""" |
| 83 | self.monitoring = False |
| 84 | if hasattr(self, 'monitor_task'): |
| 85 | self.monitor_task.cancel() |
| 86 | |
| 87 | return self.get_summary() |
| 88 | |
| 89 | def record_response_time(self, operation: str, latency: float): |
| 90 | """Record response time for operation.""" |
| 91 | self.metrics["response_times"].append({ |
| 92 | "operation": operation, |
| 93 | "latency": latency, |
| 94 | "timestamp": time.perf_counter() |
| 95 | }) |
| 96 | |
| 97 | def record_error(self, error_type: str): |
| 98 | """Record error occurrence.""" |
| 99 | self.metrics["error_counts"].append({ |