From 2866b9e7f70ebec06c0c84824747d179f03bdd86 Mon Sep 17 00:00:00 2001 From: Chris <119588753+Chris-websketch@users.noreply.github.com> Date: Tue, 18 Feb 2025 11:32:15 +0800 Subject: [PATCH] Create performance_monitor.py --- core/utils/performance_monitor.py | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 core/utils/performance_monitor.py diff --git a/core/utils/performance_monitor.py b/core/utils/performance_monitor.py new file mode 100644 index 000000000..6491f7125 --- /dev/null +++ b/core/utils/performance_monitor.py @@ -0,0 +1,49 @@ +import time +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Dict, List + +@dataclass +class ModuleStats: + total_time: float = 0.0 + call_count: int = 0 + max_time: float = 0.0 + min_time: float = float('inf') + history: List[float] = field(default_factory=list) + +class PerformanceMonitor: + def __init__(self): + self.stats: Dict[str, ModuleStats] = defaultdict(ModuleStats) + self.current_session = {} + + def record(self, module: str, duration: float): + stats = self.stats[module] + stats.total_time += duration + stats.call_count += 1 + stats.max_time = max(stats.max_time, duration) + stats.min_time = min(stats.min_time, duration) + stats.history.append(duration) + + def get_summary(self) -> Dict: + return { + module: { + "avg": stats.total_time / stats.call_count if stats.call_count else 0, + "max": stats.max_time, + "min": stats.min_time, + "total_calls": stats.call_count + } + for module, stats in self.stats.items() + } + +monitor = PerformanceMonitor() + +def track_performance(module_name: str): + def decorator(func): + def wrapper(*args, **kwargs): + start = time.perf_counter() + result = func(*args, **kwargs) + duration = time.perf_counter() - start + monitor.record(module_name, duration) + return result + return wrapper + return decorator