Coverage for /Users/les/Projects/crackerjack/crackerjack/core/performance.py: 0%
154 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import functools
2import time
3import typing as t
4from pathlib import Path
6from rich.console import Console
9class FileCache:
10 def __init__(self, ttl: float = 300.0) -> None:
11 self.ttl = ttl
12 self._cache: dict[str, tuple[float, t.Any]] = {}
14 def get(self, key: str) -> t.Any | None:
15 if key not in self._cache:
16 return None
17 timestamp, value = self._cache[key]
18 if time.time() - timestamp > self.ttl:
19 del self._cache[key]
20 return None
22 return value
24 def set(self, key: str, value: t.Any) -> None:
25 self._cache[key] = (time.time(), value)
27 def clear(self) -> None:
28 self._cache.clear()
30 def size(self) -> int:
31 return len(self._cache)
34class PerformanceMonitor:
35 def __init__(self, console: Console | None = None) -> None:
36 self.console = console
37 self.metrics: dict[str, list[float]] = {}
39 def time_operation(
40 self,
41 operation_name: str,
42 ) -> t.Callable[[t.Callable[..., t.Any]], t.Callable[..., t.Any]]:
43 def decorator(func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
44 @functools.wraps(func)
45 def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
46 start_time = time.time()
47 try:
48 return func(*args, **kwargs)
49 finally:
50 duration = time.time() - start_time
51 self.record_metric(operation_name, duration)
53 return wrapper
55 return decorator
57 def record_metric(self, name: str, value: float) -> None:
58 if name not in self.metrics:
59 self.metrics[name] = []
60 self.metrics[name].append(value)
62 def get_stats(self, name: str) -> dict[str, float]:
63 if name not in self.metrics or not self.metrics[name]:
64 return {}
65 values = self.metrics[name]
66 return {
67 "count": len(values),
68 "total": sum(values),
69 "avg": sum(values) / len(values),
70 "min": min(values),
71 "max": max(values),
72 }
74 def print_stats(self, name: str | None = None) -> None:
75 if not self.console:
76 return
77 if name:
78 stats = self.get_stats(name)
79 if stats:
80 self.console.print(
81 f"[cyan]📊 {name}: [/ cyan] "
82 f"avg={stats['avg']: .3f}s, "
83 f"min={stats['min']: .3f}s, "
84 f"max={stats['max']: .3f}s, "
85 f"count={stats['count']}",
86 )
87 else:
88 for metric_name in self.metrics:
89 self.print_stats(metric_name)
92def memoize_with_ttl(
93 ttl: float = 300.0,
94) -> t.Callable[[t.Callable[..., t.Any]], t.Callable[..., t.Any]]:
95 def decorator(func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
96 cache: dict[str, tuple[float, t.Any]] = {}
98 @functools.wraps(func)
99 def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
100 key = str(args) + str(sorted(kwargs.items()))
101 if key in cache:
102 timestamp, value = cache[key]
103 if time.time() - timestamp <= ttl:
104 return value
105 del cache[key]
106 result = func(*args, **kwargs)
107 cache[key] = (time.time(), result)
108 return result
110 setattr(wrapper, "cache_clear", cache.clear)
111 setattr(wrapper, "cache_info", lambda: {"size": len(cache), "ttl": ttl})
112 return wrapper
114 return decorator
117def batch_file_operations(
118 operations: list[t.Callable[[], t.Any]],
119 batch_size: int = 50,
120) -> list[t.Any]:
121 results: list[t.Any] = []
122 for i in range(0, len(operations), batch_size):
123 batch = operations[i : i + batch_size]
124 batch_results: list[t.Any] = []
125 for operation in batch:
126 try:
127 result = operation()
128 batch_results.append(result)
129 except Exception as e:
130 batch_results.append(e)
131 results.extend(batch_results)
132 if i + batch_size < len(operations):
133 time.sleep(0.01)
135 return results
138class OptimizedFileWatcher:
139 def __init__(self, root_path: Path) -> None:
140 self.root_path = root_path
141 self._file_cache = FileCache(ttl=60.0)
143 @memoize_with_ttl(ttl=30.0)
144 def get_python_files(self) -> list[Path]:
145 return list(self.root_path.rglob("*.py"))
147 def get_modified_files(self, since: float) -> list[Path]:
148 cache_key = f"modified_since_{since}"
149 cached = self._file_cache.get(cache_key)
150 if cached is not None:
151 return cached
152 modified_files: list[Path] = []
153 for py_file in self.get_python_files():
154 try:
155 if py_file.stat().st_mtime > since:
156 modified_files.append(py_file)
157 except (OSError, FileNotFoundError):
158 continue
159 self._file_cache.set(cache_key, modified_files)
160 return modified_files
162 def clear_cache(self) -> None:
163 self._file_cache.clear()
165 if hasattr(self.get_python_files, "cache_clear"):
166 cache_clear = getattr(self.get_python_files, "cache_clear")
167 cache_clear()
170class ParallelTaskExecutor:
171 def __init__(self, max_workers: int | None = None) -> None:
172 import os
174 self.max_workers = max_workers or min(os.cpu_count() or 1, 8)
176 def execute_tasks(
177 self,
178 tasks: list[t.Callable[[], t.Any]],
179 timeout: float = 300.0,
180 ) -> list[t.Any]:
181 if len(tasks) <= 1:
182 return [task() for task in tasks]
183 import concurrent.futures
185 results: list[tuple[int, t.Any]] = []
186 with concurrent.futures.ThreadPoolExecutor(
187 max_workers=self.max_workers,
188 ) as executor:
189 future_to_task = {executor.submit(task): i for i, task in enumerate(tasks)}
190 for future in concurrent.futures.as_completed(
191 future_to_task,
192 timeout=timeout,
193 ):
194 task_index = future_to_task[future]
195 try:
196 result = future.result()
197 results.append((task_index, result))
198 except Exception as e:
199 results.append((task_index, e))
200 import operator
202 results.sort(key=operator.itemgetter(0))
203 return [result for _, result in results]
206def optimize_subprocess_calls(
207 commands: list[list[str]],
208 cwd: Path | None = None,
209) -> list[t.Any]:
210 if len(commands) <= 1:
211 import subprocess
213 return [
214 subprocess.run(cmd, check=False, cwd=cwd, capture_output=True, text=True)
215 for cmd in commands
216 ]
217 executor = ParallelTaskExecutor()
219 def run_command(cmd: list[str]) -> t.Any:
220 import subprocess
222 return subprocess.run(cmd, check=False, cwd=cwd, capture_output=True, text=True)
224 import functools
226 tasks: list[t.Callable[[], t.Any]] = [
227 functools.partial(run_command, cmd) for cmd in commands
228 ]
229 return executor.execute_tasks(tasks)
232_performance_monitor: PerformanceMonitor | None = None
235def get_performance_monitor() -> PerformanceMonitor:
236 global _performance_monitor
237 if _performance_monitor is None:
238 _performance_monitor = PerformanceMonitor()
239 return _performance_monitor
242def reset_performance_monitor() -> None:
243 global _performance_monitor
244 _performance_monitor = None