File size: 9,589 Bytes
72fc0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""
Performance monitoring and profiling.

Provides:
  - Function execution timing
  - Performance profiling
  - Slow query detection
  - Resource usage tracking
  - Performance reports
"""

from __future__ import annotations

import functools
import logging
import time
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Optional

log = logging.getLogger(__name__)


@dataclass
class PerformanceMetrics:
    """Performance metrics for a function or operation."""
    name: str
    call_count: int = 0
    total_time: float = 0.0
    min_time: float = float('inf')
    max_time: float = 0.0
    errors: int = 0
    
    @property
    def avg_time(self) -> float:
        """Average execution time."""
        return self.total_time / self.call_count if self.call_count > 0 else 0.0
    
    def record(self, duration: float, error: bool = False):
        """
        Record a new measurement.
        
        Parameters
        ----------
        duration : float
            Execution duration (seconds)
        error : bool
            Whether an error occurred
        """
        self.call_count += 1
        self.total_time += duration
        self.min_time = min(self.min_time, duration)
        self.max_time = max(self.max_time, duration)
        
        if error:
            self.errors += 1
    
    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary."""
        return {
            'name': self.name,
            'call_count': self.call_count,
            'total_time': self.total_time,
            'avg_time': self.avg_time,
            'min_time': self.min_time if self.min_time != float('inf') else 0.0,
            'max_time': self.max_time,
            'errors': self.errors,
        }


class PerformanceMonitor:
    """Global performance monitor."""
    
    def __init__(self):
        """Initialize performance monitor."""
        self._metrics: dict[str, PerformanceMetrics] = defaultdict(
            lambda: PerformanceMetrics(name="unknown")
        )
        self._slow_threshold: float = 1.0  # seconds
        self._slow_operations: list[dict] = []
    
    def record(self, name: str, duration: float, error: bool = False):
        """
        Record performance metric.
        
        Parameters
        ----------
        name : str
            Operation name
        duration : float
            Duration (seconds)
        error : bool
            Whether an error occurred
        """
        if name not in self._metrics:
            self._metrics[name] = PerformanceMetrics(name=name)
        
        self._metrics[name].record(duration, error)
        
        # Track slow operations
        if duration > self._slow_threshold:
            self._slow_operations.append({
                'name': name,
                'duration': duration,
                'timestamp': time.time(),
            })
            
            # Keep only last 100 slow operations
            if len(self._slow_operations) > 100:
                self._slow_operations = self._slow_operations[-100:]
            
            log.warning(f"Slow operation detected: {name} took {duration:.3f}s")
    
    def get_metrics(self, name: Optional[str] = None) -> dict[str, PerformanceMetrics] | PerformanceMetrics:
        """
        Get performance metrics.
        
        Parameters
        ----------
        name : str, optional
            Specific metric name, or None for all metrics
        
        Returns
        -------
        dict or PerformanceMetrics
            Requested metrics
        """
        if name is not None:
            return self._metrics.get(name, PerformanceMetrics(name=name))
        return dict(self._metrics)
    
    def get_slow_operations(self) -> list[dict]:
        """Get recent slow operations."""
        return self._slow_operations.copy()
    
    def reset(self):
        """Reset all metrics."""
        self._metrics.clear()
        self._slow_operations.clear()
    
    def set_slow_threshold(self, seconds: float):
        """Set slow operation threshold."""
        self._slow_threshold = seconds
    
    def generate_report(self) -> dict[str, Any]:
        """
        Generate performance report.
        
        Returns
        -------
        dict
            Performance report
        """
        sorted_metrics = sorted(
            self._metrics.values(),
            key=lambda m: m.total_time,
            reverse=True
        )
        
        return {
            'total_operations': sum(m.call_count for m in self._metrics.values()),
            'total_time': sum(m.total_time for m in self._metrics.values()),
            'total_errors': sum(m.errors for m in self._metrics.values()),
            'top_time_consumers': [m.to_dict() for m in sorted_metrics[:10]],
            'slow_operations_count': len(self._slow_operations),
            'recent_slow_operations': self._slow_operations[-10:],
        }


# === Global Monitor ===

_performance_monitor = PerformanceMonitor()


def get_performance_monitor() -> PerformanceMonitor:
    """Get global performance monitor."""
    return _performance_monitor


# === Decorators ===

def monitor_performance(name: Optional[str] = None):
    """
    Decorator to monitor function performance.
    
    Usage:
        @monitor_performance('my_function')
        def my_function():
            ...
    
    Parameters
    ----------
    name : str, optional
        Custom name for the operation (default: function name)
    """
    def decorator(func: Callable) -> Callable:
        operation_name = name or f"{func.__module__}.{func.__name__}"
        
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            start = time.perf_counter()
            error = False
            
            try:
                result = func(*args, **kwargs)
                return result
            except Exception:
                error = True
                raise
            finally:
                duration = time.perf_counter() - start
                _performance_monitor.record(operation_name, duration, error)
        
        return wrapper
    return decorator


@contextmanager
def track_performance(name: str):
    """
    Context manager to track performance.
    
    Usage:
        with track_performance('database_query'):
            results = db.query(...)
    
    Parameters
    ----------
    name : str
        Operation name
    """
    start = time.perf_counter()
    error = False
    
    try:
        yield
    except Exception:
        error = True
        raise
    finally:
        duration = time.perf_counter() - start
        _performance_monitor.record(name, duration, error)


@contextmanager
def profile_section(label: str):
    """
    Context manager to profile a code section.
    
    Logs timing information for the section.
    
    Parameters
    ----------
    label : str
        Section label
    """
    start = time.perf_counter()
    log.debug(f"Starting: {label}")
    
    try:
        yield
    finally:
        duration = time.perf_counter() - start
        log.info(f"Completed: {label} in {duration:.3f}s")


class PerformanceTimer:
    """Manual performance timer."""
    
    def __init__(self, name: str, auto_record: bool = True):
        """
        Initialize timer.
        
        Parameters
        ----------
        name : str
            Timer name
        auto_record : bool
            Automatically record to global monitor on stop
        """
        self.name = name
        self.auto_record = auto_record
        self.start_time: Optional[float] = None
        self.duration: Optional[float] = None
    
    def start(self):
        """Start the timer."""
        self.start_time = time.perf_counter()
        return self
    
    def stop(self) -> float:
        """
        Stop the timer.
        
        Returns
        -------
        float
            Duration in seconds
        """
        if self.start_time is None:
            raise RuntimeError("Timer not started")
        
        self.duration = time.perf_counter() - self.start_time
        
        if self.auto_record:
            _performance_monitor.record(self.name, self.duration)
        
        return self.duration
    
    def __enter__(self):
        """Context manager entry."""
        self.start()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """Context manager exit."""
        self.stop()


def time_function(func: Callable) -> float:
    """
    Time a function call (single execution).
    
    Parameters
    ----------
    func : Callable
        Function to time
    
    Returns
    -------
    float
        Execution time in seconds
    """
    start = time.perf_counter()
    func()
    return time.perf_counter() - start


def benchmark(func: Callable, iterations: int = 100) -> dict[str, float]:
    """
    Benchmark a function over multiple iterations.
    
    Parameters
    ----------
    func : Callable
        Function to benchmark
    iterations : int
        Number of iterations
    
    Returns
    -------
    dict
        Benchmark results (mean, min, max, total)
    """
    times = []
    
    for _ in range(iterations):
        start = time.perf_counter()
        func()
        times.append(time.perf_counter() - start)
    
    return {
        'iterations': iterations,
        'mean': sum(times) / len(times),
        'min': min(times),
        'max': max(times),
        'total': sum(times),
    }