- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py. - Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files. - Updated install_dependencies.py to improve dependency installation prompts. - Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability. - Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries. - Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability. - Updated __init__.py in typings to remove unnecessary lines. - Modified app.js to adjust default configuration values and clean up unused code.
68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
"""性能追踪模块:耗时统计与简单分析工具"""
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
import threading
|
|
from typing import Callable, Dict, List, Optional
|
|
|
|
class PerformanceTracker:
|
|
def __init__(self) -> None:
|
|
self._start_times: Dict[str, float] = {}
|
|
self._durations: Dict[str, List[float]] = {}
|
|
self._lock = threading.Lock()
|
|
|
|
def start_timer(self, name: str) -> str:
|
|
with self._lock:
|
|
timer_id = f"{name}-{int(time.time()*1000)}"
|
|
self._start_times[timer_id] = time.perf_counter()
|
|
return timer_id
|
|
|
|
def end_timer(self, timer_id: str) -> float:
|
|
with self._lock:
|
|
start = self._start_times.pop(timer_id, None)
|
|
if start is None:
|
|
return 0.0
|
|
elapsed = time.perf_counter() - start
|
|
self._durations.setdefault(timer_id.split("-")[0], []).append(elapsed)
|
|
return elapsed
|
|
|
|
def get_elapsed(self, timer_id: str) -> float:
|
|
with self._lock:
|
|
start = self._start_times.get(timer_id)
|
|
if start is None:
|
|
return 0.0
|
|
return time.perf_counter() - start
|
|
|
|
def track_function(self, func: Callable) -> Callable:
|
|
def wrapper(*args, **kwargs):
|
|
name = func.__qualname__
|
|
timer = self.start_timer(name)
|
|
try:
|
|
result = func(*args, **kwargs)
|
|
return result
|
|
finally:
|
|
self.end_timer(timer)
|
|
return wrapper
|
|
|
|
def track_step(self, name: str) -> Callable:
|
|
def decorator(func: Callable) -> Callable:
|
|
def inner(*args, **kwargs):
|
|
t = self.start_timer(name)
|
|
try:
|
|
return func(*args, **kwargs)
|
|
finally:
|
|
self.end_timer(t)
|
|
return inner
|
|
return decorator
|
|
|
|
def get_statistics(self) -> Dict[str, float]:
|
|
# 返回一个简单的平均耗时统计字典,使用最近的 durations
|
|
with self._lock:
|
|
stats = {}
|
|
for key, arr in self._durations.items():
|
|
if arr:
|
|
stats[key] = sum(arr) / len(arr)
|
|
return stats
|
|
|
|
__all__ = ["PerformanceTracker"]
|