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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Performance Optimization Module
|
| 4 |
+
|
| 5 |
+
Provides system optimization features, resource monitoring, and performance
|
| 6 |
+
analytics for the GPU monitoring system.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import time
|
| 10 |
+
import psutil
|
| 11 |
+
import logging
|
| 12 |
+
import threading
|
| 13 |
+
import json
|
| 14 |
+
from typing import Dict, List, Optional, Tuple, Any
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class SystemMetrics:
|
| 24 |
+
"""System performance metrics."""
|
| 25 |
+
timestamp: float
|
| 26 |
+
cpu_percent: float
|
| 27 |
+
memory_percent: float
|
| 28 |
+
disk_percent: float
|
| 29 |
+
network_sent: int
|
| 30 |
+
network_recv: int
|
| 31 |
+
process_count: int
|
| 32 |
+
load_avg: Tuple[float, float, float]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class GPUMetrics:
|
| 37 |
+
"""GPU performance metrics."""
|
| 38 |
+
timestamp: float
|
| 39 |
+
temperature: float
|
| 40 |
+
load: float
|
| 41 |
+
power_draw: float
|
| 42 |
+
fan_speed: int
|
| 43 |
+
memory_usage: float
|
| 44 |
+
efficiency: float
|
| 45 |
+
core_clock: int
|
| 46 |
+
memory_clock: int
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass
|
| 50 |
+
class OptimizationProfile:
|
| 51 |
+
"""System optimization profile."""
|
| 52 |
+
name: str
|
| 53 |
+
description: str
|
| 54 |
+
settings: Dict[str, Any]
|
| 55 |
+
enabled: bool = True
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class SystemOptimizer:
|
| 59 |
+
"""System performance optimizer."""
|
| 60 |
+
|
| 61 |
+
def __init__(self, config_file: str = "config/optimization.json"):
|
| 62 |
+
self.config_file = config_file
|
| 63 |
+
self.profiles = {}
|
| 64 |
+
self.current_profile = None
|
| 65 |
+
self.monitoring = False
|
| 66 |
+
self.monitor_thread = None
|
| 67 |
+
|
| 68 |
+
# Performance data
|
| 69 |
+
self.system_history = []
|
| 70 |
+
self.gpu_history = []
|
| 71 |
+
|
| 72 |
+
# Load configuration
|
| 73 |
+
self.load_config()
|
| 74 |
+
|
| 75 |
+
def load_config(self):
|
| 76 |
+
"""Load optimization configuration."""
|
| 77 |
+
try:
|
| 78 |
+
if Path(self.config_file).exists():
|
| 79 |
+
with open(self.config_file, 'r') as f:
|
| 80 |
+
config = json.load(f)
|
| 81 |
+
|
| 82 |
+
# Load profiles
|
| 83 |
+
for name, profile_data in config.get('profiles', {}).items():
|
| 84 |
+
profile = OptimizationProfile(
|
| 85 |
+
name=name,
|
| 86 |
+
description=profile_data['description'],
|
| 87 |
+
settings=profile_data['settings'],
|
| 88 |
+
enabled=profile_data.get('enabled', True)
|
| 89 |
+
)
|
| 90 |
+
self.profiles[name] = profile
|
| 91 |
+
|
| 92 |
+
# Set current profile
|
| 93 |
+
default_profile = config.get('default_profile', 'balanced')
|
| 94 |
+
if default_profile in self.profiles:
|
| 95 |
+
self.current_profile = self.profiles[default_profile]
|
| 96 |
+
|
| 97 |
+
logger.info(f"Loaded {len(self.profiles)} optimization profiles")
|
| 98 |
+
else:
|
| 99 |
+
self.create_default_config()
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Error loading optimization config: {e}")
|
| 103 |
+
self.create_default_config()
|
| 104 |
+
|
| 105 |
+
def create_default_config(self):
|
| 106 |
+
"""Create default optimization configuration."""
|
| 107 |
+
default_config = {
|
| 108 |
+
"profiles": {
|
| 109 |
+
"power_saving": {
|
| 110 |
+
"name": "Power Saving",
|
| 111 |
+
"description": "Optimize for minimum power consumption",
|
| 112 |
+
"settings": {
|
| 113 |
+
"cpu_governor": "powersave",
|
| 114 |
+
"gpu_power_target": 150,
|
| 115 |
+
"fan_curve": "silent",
|
| 116 |
+
"monitoring_interval": 5.0,
|
| 117 |
+
"data_retention": 3600
|
| 118 |
+
},
|
| 119 |
+
"enabled": True
|
| 120 |
+
},
|
| 121 |
+
"balanced": {
|
| 122 |
+
"name": "Balanced",
|
| 123 |
+
"description": "Balance between performance and power",
|
| 124 |
+
"settings": {
|
| 125 |
+
"cpu_governor": "ondemand",
|
| 126 |
+
"gpu_power_target": 200,
|
| 127 |
+
"fan_curve": "balanced",
|
| 128 |
+
"monitoring_interval": 2.0,
|
| 129 |
+
"data_retention": 7200
|
| 130 |
+
},
|
| 131 |
+
"enabled": True
|
| 132 |
+
},
|
| 133 |
+
"performance": {
|
| 134 |
+
"name": "Performance",
|
| 135 |
+
"description": "Optimize for maximum performance",
|
| 136 |
+
"settings": {
|
| 137 |
+
"cpu_governor": "performance",
|
| 138 |
+
"gpu_power_target": 250,
|
| 139 |
+
"fan_curve": "performance",
|
| 140 |
+
"monitoring_interval": 1.0,
|
| 141 |
+
"data_retention": 14400
|
| 142 |
+
},
|
| 143 |
+
"enabled": True
|
| 144 |
+
},
|
| 145 |
+
"gaming": {
|
| 146 |
+
"name": "Gaming",
|
| 147 |
+
"description": "Optimize for gaming performance",
|
| 148 |
+
"settings": {
|
| 149 |
+
"cpu_governor": "performance",
|
| 150 |
+
"gpu_power_target": 250,
|
| 151 |
+
"fan_curve": "performance",
|
| 152 |
+
"monitoring_interval": 0.5,
|
| 153 |
+
"data_retention": 28800,
|
| 154 |
+
"disable_screen_blank": True,
|
| 155 |
+
"disable_power_save": True
|
| 156 |
+
},
|
| 157 |
+
"enabled": True
|
| 158 |
+
}
|
| 159 |
+
},
|
| 160 |
+
"default_profile": "balanced",
|
| 161 |
+
"monitoring": {
|
| 162 |
+
"enabled": True,
|
| 163 |
+
"interval": 2.0,
|
| 164 |
+
"max_history": 1000
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
# Save default config
|
| 169 |
+
Path(self.config_file).parent.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
with open(self.config_file, 'w') as f:
|
| 171 |
+
json.dump(default_config, f, indent=2)
|
| 172 |
+
|
| 173 |
+
logger.info("Created default optimization configuration")
|
| 174 |
+
|
| 175 |
+
def apply_profile(self, profile_name: str) -> bool:
|
| 176 |
+
"""Apply optimization profile."""
|
| 177 |
+
if profile_name not in self.profiles:
|
| 178 |
+
logger.error(f"Profile '{profile_name}' not found")
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
+
profile = self.profiles[profile_name]
|
| 182 |
+
if not profile.enabled:
|
| 183 |
+
logger.error(f"Profile '{profile_name}' is disabled")
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
try:
|
| 187 |
+
# Apply CPU governor
|
| 188 |
+
cpu_governor = profile.settings.get('cpu_governor')
|
| 189 |
+
if cpu_governor:
|
| 190 |
+
self.set_cpu_governor(cpu_governor)
|
| 191 |
+
|
| 192 |
+
# Apply GPU power target
|
| 193 |
+
gpu_power = profile.settings.get('gpu_power_target')
|
| 194 |
+
if gpu_power:
|
| 195 |
+
self.set_gpu_power_target(gpu_power)
|
| 196 |
+
|
| 197 |
+
# Apply fan curve
|
| 198 |
+
fan_curve = profile.settings.get('fan_curve')
|
| 199 |
+
if fan_curve:
|
| 200 |
+
self.set_fan_curve(fan_curve)
|
| 201 |
+
|
| 202 |
+
# Apply monitoring settings
|
| 203 |
+
monitoring_interval = profile.settings.get('monitoring_interval')
|
| 204 |
+
if monitoring_interval:
|
| 205 |
+
self.update_monitoring_interval(monitoring_interval)
|
| 206 |
+
|
| 207 |
+
self.current_profile = profile
|
| 208 |
+
logger.info(f"Applied optimization profile: {profile.name}")
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
except Exception as e:
|
| 212 |
+
logger.error(f"Error applying profile '{profile_name}': {e}")
|
| 213 |
+
return False
|
| 214 |
+
|
| 215 |
+
def set_cpu_governor(self, governor: str):
|
| 216 |
+
"""Set CPU frequency governor."""
|
| 217 |
+
try:
|
| 218 |
+
# Get available governors
|
| 219 |
+
with open('/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors', 'r') as f:
|
| 220 |
+
available = f.read().strip().split()
|
| 221 |
+
|
| 222 |
+
if governor not in available:
|
| 223 |
+
logger.warning(f"Governor '{governor}' not available, using 'ondemand'")
|
| 224 |
+
governor = 'ondemand'
|
| 225 |
+
|
| 226 |
+
# Set governor for all CPUs
|
| 227 |
+
for cpu in range(psutil.cpu_count()):
|
| 228 |
+
governor_file = f'/sys/devices/system/cpu/cpu{cpu}/cpufreq/scaling_governor'
|
| 229 |
+
try:
|
| 230 |
+
with open(governor_file, 'w') as f:
|
| 231 |
+
f.write(governor)
|
| 232 |
+
except PermissionError:
|
| 233 |
+
logger.warning(f"Cannot set governor for CPU {cpu}, insufficient permissions")
|
| 234 |
+
|
| 235 |
+
logger.info(f"Set CPU governor to: {governor}")
|
| 236 |
+
|
| 237 |
+
except Exception as e:
|
| 238 |
+
logger.error(f"Error setting CPU governor: {e}")
|
| 239 |
+
|
| 240 |
+
def set_gpu_power_target(self, power_target: int):
|
| 241 |
+
"""Set GPU power target."""
|
| 242 |
+
try:
|
| 243 |
+
# This would need to be implemented based on the specific GPU driver
|
| 244 |
+
# For AMD GPUs, this might involve writing to sysfs files
|
| 245 |
+
logger.info(f"Set GPU power target to: {power_target}W")
|
| 246 |
+
|
| 247 |
+
except Exception as e:
|
| 248 |
+
logger.error(f"Error setting GPU power target: {e}")
|
| 249 |
+
|
| 250 |
+
def set_fan_curve(self, curve_name: str):
|
| 251 |
+
"""Set fan curve profile."""
|
| 252 |
+
try:
|
| 253 |
+
# This would integrate with the fan controller
|
| 254 |
+
logger.info(f"Set fan curve to: {curve_name}")
|
| 255 |
+
|
| 256 |
+
except Exception as e:
|
| 257 |
+
logger.error(f"Error setting fan curve: {e}")
|
| 258 |
+
|
| 259 |
+
def update_monitoring_interval(self, interval: float):
|
| 260 |
+
"""Update monitoring interval."""
|
| 261 |
+
# This would update the monitoring system interval
|
| 262 |
+
logger.info(f"Updated monitoring interval to: {interval}s")
|
| 263 |
+
|
| 264 |
+
def start_monitoring(self):
|
| 265 |
+
"""Start performance monitoring."""
|
| 266 |
+
if self.monitoring:
|
| 267 |
+
return
|
| 268 |
+
|
| 269 |
+
self.monitoring = True
|
| 270 |
+
self.monitor_thread = threading.Thread(target=self.monitor_loop, daemon=True)
|
| 271 |
+
self.monitor_thread.start()
|
| 272 |
+
logger.info("Started performance monitoring")
|
| 273 |
+
|
| 274 |
+
def stop_monitoring(self):
|
| 275 |
+
"""Stop performance monitoring."""
|
| 276 |
+
self.monitoring = False
|
| 277 |
+
if self.monitor_thread:
|
| 278 |
+
self.monitor_thread.join()
|
| 279 |
+
logger.info("Stopped performance monitoring")
|
| 280 |
+
|
| 281 |
+
def monitor_loop(self):
|
| 282 |
+
"""Main monitoring loop."""
|
| 283 |
+
interval = self.profiles.get('monitoring', {}).get('interval', 2.0)
|
| 284 |
+
max_history = self.profiles.get('monitoring', {}).get('max_history', 1000)
|
| 285 |
+
|
| 286 |
+
while self.monitoring:
|
| 287 |
+
try:
|
| 288 |
+
# Collect system metrics
|
| 289 |
+
system_metrics = self.collect_system_metrics()
|
| 290 |
+
self.system_history.append(system_metrics)
|
| 291 |
+
|
| 292 |
+
# Limit history size
|
| 293 |
+
if len(self.system_history) > max_history:
|
| 294 |
+
self.system_history.pop(0)
|
| 295 |
+
|
| 296 |
+
# Collect GPU metrics (would integrate with GPU monitoring)
|
| 297 |
+
gpu_metrics = self.collect_gpu_metrics()
|
| 298 |
+
if gpu_metrics:
|
| 299 |
+
self.gpu_history.append(gpu_metrics)
|
| 300 |
+
|
| 301 |
+
# Limit GPU history size
|
| 302 |
+
if len(self.gpu_history) > max_history:
|
| 303 |
+
self.gpu_history.pop(0)
|
| 304 |
+
|
| 305 |
+
time.sleep(interval)
|
| 306 |
+
|
| 307 |
+
except Exception as e:
|
| 308 |
+
logger.error(f"Error in monitoring loop: {e}")
|
| 309 |
+
time.sleep(5)
|
| 310 |
+
|
| 311 |
+
def collect_system_metrics(self) -> SystemMetrics:
|
| 312 |
+
"""Collect current system metrics."""
|
| 313 |
+
# CPU metrics
|
| 314 |
+
cpu_percent = psutil.cpu_percent(interval=1)
|
| 315 |
+
load_avg = psutil.getloadavg()
|
| 316 |
+
|
| 317 |
+
# Memory metrics
|
| 318 |
+
memory = psutil.virtual_memory()
|
| 319 |
+
memory_percent = memory.percent
|
| 320 |
+
|
| 321 |
+
# Disk metrics
|
| 322 |
+
disk = psutil.disk_usage('/')
|
| 323 |
+
disk_percent = (disk.used / disk.total) * 100
|
| 324 |
+
|
| 325 |
+
# Network metrics
|
| 326 |
+
network = psutil.net_io_counters()
|
| 327 |
+
|
| 328 |
+
# Process count
|
| 329 |
+
process_count = len(psutil.pids())
|
| 330 |
+
|
| 331 |
+
return SystemMetrics(
|
| 332 |
+
timestamp=time.time(),
|
| 333 |
+
cpu_percent=cpu_percent,
|
| 334 |
+
memory_percent=memory_percent,
|
| 335 |
+
disk_percent=disk_percent,
|
| 336 |
+
network_sent=network.bytes_sent,
|
| 337 |
+
network_recv=network.bytes_recv,
|
| 338 |
+
process_count=process_count,
|
| 339 |
+
load_avg=load_avg
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
def collect_gpu_metrics(self) -> Optional[GPUMetrics]:
|
| 343 |
+
"""Collect current GPU metrics."""
|
| 344 |
+
try:
|
| 345 |
+
# This would integrate with the GPU monitoring system
|
| 346 |
+
# For now, return dummy data
|
| 347 |
+
return GPUMetrics(
|
| 348 |
+
timestamp=time.time(),
|
| 349 |
+
temperature=65.0,
|
| 350 |
+
load=45.0,
|
| 351 |
+
power_draw=150.0,
|
| 352 |
+
fan_speed=1800,
|
| 353 |
+
memory_usage=60.0,
|
| 354 |
+
efficiency=0.3,
|
| 355 |
+
core_clock=1500,
|
| 356 |
+
memory_clock=1000
|
| 357 |
+
)
|
| 358 |
+
except:
|
| 359 |
+
return None
|
| 360 |
+
|
| 361 |
+
def get_performance_analytics(self, hours: int = 24) -> Dict[str, Any]:
|
| 362 |
+
"""Get performance analytics for the specified time period."""
|
| 363 |
+
cutoff_time = time.time() - (hours * 3600)
|
| 364 |
+
|
| 365 |
+
# Filter recent data
|
| 366 |
+
recent_system = [m for m in self.system_history if m.timestamp >= cutoff_time]
|
| 367 |
+
recent_gpu = [m for m in self.gpu_history if m.timestamp >= cutoff_time]
|
| 368 |
+
|
| 369 |
+
if not recent_system:
|
| 370 |
+
return {"error": "No performance data available"}
|
| 371 |
+
|
| 372 |
+
# Calculate system analytics
|
| 373 |
+
cpu_values = [m.cpu_percent for m in recent_system]
|
| 374 |
+
memory_values = [m.memory_percent for m in recent_system]
|
| 375 |
+
disk_values = [m.disk_percent for m in recent_system]
|
| 376 |
+
|
| 377 |
+
system_analytics = {
|
| 378 |
+
"cpu": {
|
| 379 |
+
"avg": sum(cpu_values) / len(cpu_values),
|
| 380 |
+
"max": max(cpu_values),
|
| 381 |
+
"min": min(cpu_values),
|
| 382 |
+
"current": cpu_values[-1] if cpu_values else 0
|
| 383 |
+
},
|
| 384 |
+
"memory": {
|
| 385 |
+
"avg": sum(memory_values) / len(memory_values),
|
| 386 |
+
"max": max(memory_values),
|
| 387 |
+
"min": min(memory_values),
|
| 388 |
+
"current": memory_values[-1] if memory_values else 0
|
| 389 |
+
},
|
| 390 |
+
"disk": {
|
| 391 |
+
"avg": sum(disk_values) / len(disk_values),
|
| 392 |
+
"max": max(disk_values),
|
| 393 |
+
"min": min(disk_values),
|
| 394 |
+
"current": disk_values[-1] if disk_values else 0
|
| 395 |
+
},
|
| 396 |
+
"network": {
|
| 397 |
+
"total_sent": recent_system[-1].network_sent - recent_system[0].network_sent if len(recent_system) > 1 else 0,
|
| 398 |
+
"total_recv": recent_system[-1].network_recv - recent_system[0].network_recv if len(recent_system) > 1 else 0
|
| 399 |
+
},
|
| 400 |
+
"processes": {
|
| 401 |
+
"avg": sum(m.process_count for m in recent_system) / len(recent_system),
|
| 402 |
+
"max": max(m.process_count for m in recent_system),
|
| 403 |
+
"min": min(m.process_count for m in recent_system),
|
| 404 |
+
"current": recent_system[-1].process_count if recent_system else 0
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
# Calculate GPU analytics if available
|
| 409 |
+
gpu_analytics = {}
|
| 410 |
+
if recent_gpu:
|
| 411 |
+
temp_values = [m.temperature for m in recent_gpu]
|
| 412 |
+
load_values = [m.load for m in recent_gpu]
|
| 413 |
+
power_values = [m.power_draw for m in recent_gpu]
|
| 414 |
+
|
| 415 |
+
gpu_analytics = {
|
| 416 |
+
"temperature": {
|
| 417 |
+
"avg": sum(temp_values) / len(temp_values),
|
| 418 |
+
"max": max(temp_values),
|
| 419 |
+
"min": min(temp_values),
|
| 420 |
+
"current": temp_values[-1] if temp_values else 0
|
| 421 |
+
},
|
| 422 |
+
"load": {
|
| 423 |
+
"avg": sum(load_values) / len(load_values),
|
| 424 |
+
"max": max(load_values),
|
| 425 |
+
"min": min(load_values),
|
| 426 |
+
"current": load_values[-1] if load_values else 0
|
| 427 |
+
},
|
| 428 |
+
"power": {
|
| 429 |
+
"avg": sum(power_values) / len(power_values),
|
| 430 |
+
"max": max(power_values),
|
| 431 |
+
"min": min(power_values),
|
| 432 |
+
"current": power_values[-1] if power_values else 0
|
| 433 |
+
}
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
return {
|
| 437 |
+
"system": system_analytics,
|
| 438 |
+
"gpu": gpu_analytics,
|
| 439 |
+
"time_range": {
|
| 440 |
+
"start": cutoff_time,
|
| 441 |
+
"end": time.time(),
|
| 442 |
+
"hours": hours
|
| 443 |
+
},
|
| 444 |
+
"data_points": {
|
| 445 |
+
"system": len(recent_system),
|
| 446 |
+
"gpu": len(recent_gpu)
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
def optimize_for_application(self, app_name: str) -> bool:
|
| 451 |
+
"""Optimize system for specific application."""
|
| 452 |
+
# Application-specific optimizations
|
| 453 |
+
app_profiles = {
|
| 454 |
+
"gaming": "gaming",
|
| 455 |
+
"video_editing": "performance",
|
| 456 |
+
"office": "power_saving",
|
| 457 |
+
"browsing": "balanced",
|
| 458 |
+
"development": "balanced"
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
profile_name = app_profiles.get(app_name.lower(), "balanced")
|
| 462 |
+
return self.apply_profile(profile_name)
|
| 463 |
+
|
| 464 |
+
def get_recommendations(self) -> List[Dict[str, Any]]:
|
| 465 |
+
"""Get performance optimization recommendations."""
|
| 466 |
+
recommendations = []
|
| 467 |
+
|
| 468 |
+
if not self.system_history:
|
| 469 |
+
return [{"type": "info", "message": "No performance data available for recommendations"}]
|
| 470 |
+
|
| 471 |
+
latest_metrics = self.system_history[-1]
|
| 472 |
+
|
| 473 |
+
# CPU recommendations
|
| 474 |
+
if latest_metrics.cpu_percent > 80:
|
| 475 |
+
recommendations.append({
|
| 476 |
+
"type": "warning",
|
| 477 |
+
"category": "CPU",
|
| 478 |
+
"message": "High CPU usage detected. Consider closing unnecessary applications or upgrading CPU.",
|
| 479 |
+
"action": "Apply performance profile or reduce system load"
|
| 480 |
+
})
|
| 481 |
+
|
| 482 |
+
# Memory recommendations
|
| 483 |
+
if latest_metrics.memory_percent > 80:
|
| 484 |
+
recommendations.append({
|
| 485 |
+
"type": "warning",
|
| 486 |
+
"category": "Memory",
|
| 487 |
+
"message": "High memory usage detected. Consider closing memory-intensive applications.",
|
| 488 |
+
"action": "Close unnecessary applications or add more RAM"
|
| 489 |
+
})
|
| 490 |
+
|
| 491 |
+
# Disk recommendations
|
| 492 |
+
if latest_metrics.disk_percent > 90:
|
| 493 |
+
recommendations.append({
|
| 494 |
+
"type": "critical",
|
| 495 |
+
"category": "Disk",
|
| 496 |
+
"message": "Disk space critically low. This may impact system performance.",
|
| 497 |
+
"action": "Free up disk space immediately"
|
| 498 |
+
})
|
| 499 |
+
|
| 500 |
+
# GPU recommendations (if available)
|
| 501 |
+
if self.gpu_history:
|
| 502 |
+
latest_gpu = self.gpu_history[-1]
|
| 503 |
+
if latest_gpu.temperature > 80:
|
| 504 |
+
recommendations.append({
|
| 505 |
+
"type": "warning",
|
| 506 |
+
"category": "GPU",
|
| 507 |
+
"message": "High GPU temperature detected. Check cooling system.",
|
| 508 |
+
"action": "Apply performance fan curve or improve cooling"
|
| 509 |
+
})
|
| 510 |
+
|
| 511 |
+
# General recommendations
|
| 512 |
+
if not recommendations:
|
| 513 |
+
recommendations.append({
|
| 514 |
+
"type": "info",
|
| 515 |
+
"category": "System",
|
| 516 |
+
"message": "System performance appears optimal.",
|
| 517 |
+
"action": "Continue monitoring and maintain current settings"
|
| 518 |
+
})
|
| 519 |
+
|
| 520 |
+
return recommendations
|
| 521 |
+
|
| 522 |
+
def save_performance_report(self, filename: str = None) -> str:
|
| 523 |
+
"""Save performance report to file."""
|
| 524 |
+
if not filename:
|
| 525 |
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| 526 |
+
filename = f"performance_report_{timestamp}.json"
|
| 527 |
+
|
| 528 |
+
analytics = self.get_performance_analytics(24)
|
| 529 |
+
recommendations = self.get_recommendations()
|
| 530 |
+
|
| 531 |
+
report = {
|
| 532 |
+
"timestamp": time.time(),
|
| 533 |
+
"report_period": "24 hours",
|
| 534 |
+
"analytics": analytics,
|
| 535 |
+
"recommendations": recommendations,
|
| 536 |
+
"current_profile": self.current_profile.name if self.current_profile else "unknown"
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
# Save report
|
| 540 |
+
Path("reports").mkdir(exist_ok=True)
|
| 541 |
+
report_path = Path("reports") / filename
|
| 542 |
+
|
| 543 |
+
with open(report_path, 'w') as f:
|
| 544 |
+
json.dump(report, f, indent=2, default=str)
|
| 545 |
+
|
| 546 |
+
logger.info(f"Performance report saved to: {report_path}")
|
| 547 |
+
return str(report_path)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class PerformanceAPI:
|
| 551 |
+
"""API interface for performance optimization."""
|
| 552 |
+
|
| 553 |
+
def __init__(self, optimizer: SystemOptimizer):
|
| 554 |
+
self.optimizer = optimizer
|
| 555 |
+
|
| 556 |
+
def get_profiles(self) -> Dict[str, Any]:
|
| 557 |
+
"""Get available optimization profiles."""
|
| 558 |
+
profiles = {}
|
| 559 |
+
for name, profile in self.optimizer.profiles.items():
|
| 560 |
+
profiles[name] = {
|
| 561 |
+
"name": profile.name,
|
| 562 |
+
"description": profile.description,
|
| 563 |
+
"settings": profile.settings,
|
| 564 |
+
"enabled": profile.enabled
|
| 565 |
+
}
|
| 566 |
+
return profiles
|
| 567 |
+
|
| 568 |
+
def apply_profile(self, profile_name: str) -> Dict[str, Any]:
|
| 569 |
+
"""Apply optimization profile."""
|
| 570 |
+
success = self.optimizer.apply_profile(profile_name)
|
| 571 |
+
return {
|
| 572 |
+
"success": success,
|
| 573 |
+
"message": f"Applied profile: {profile_name}" if success else f"Failed to apply profile: {profile_name}"
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
def get_current_profile(self) -> Dict[str, Any]:
|
| 577 |
+
"""Get current optimization profile."""
|
| 578 |
+
if self.optimizer.current_profile:
|
| 579 |
+
profile = self.optimizer.current_profile
|
| 580 |
+
return {
|
| 581 |
+
"name": profile.name,
|
| 582 |
+
"description": profile.description,
|
| 583 |
+
"settings": profile.settings,
|
| 584 |
+
"enabled": profile.enabled
|
| 585 |
+
}
|
| 586 |
+
return {"error": "No profile currently applied"}
|
| 587 |
+
|
| 588 |
+
def get_performance_analytics(self, hours: int = 24) -> Dict[str, Any]:
|
| 589 |
+
"""Get performance analytics."""
|
| 590 |
+
return self.optimizer.get_performance_analytics(hours)
|
| 591 |
+
|
| 592 |
+
def get_recommendations(self) -> List[Dict[str, Any]]:
|
| 593 |
+
"""Get optimization recommendations."""
|
| 594 |
+
return self.optimizer.get_recommendations()
|
| 595 |
+
|
| 596 |
+
def optimize_for_application(self, app_name: str) -> Dict[str, Any]:
|
| 597 |
+
"""Optimize for specific application."""
|
| 598 |
+
success = self.optimizer.optimize_for_application(app_name)
|
| 599 |
+
return {
|
| 600 |
+
"success": success,
|
| 601 |
+
"message": f"Optimized for {app_name}" if success else f"Failed to optimize for {app_name}"
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
def save_report(self, filename: str = None) -> Dict[str, Any]:
|
| 605 |
+
"""Save performance report."""
|
| 606 |
+
try:
|
| 607 |
+
report_path = self.optimizer.save_performance_report(filename)
|
| 608 |
+
return {
|
| 609 |
+
"success": True,
|
| 610 |
+
"report_path": report_path
|
| 611 |
+
}
|
| 612 |
+
except Exception as e:
|
| 613 |
+
return {
|
| 614 |
+
"success": False,
|
| 615 |
+
"error": str(e)
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
if __name__ == "__main__":
|
| 620 |
+
# Test performance optimizer
|
| 621 |
+
logging.basicConfig(level=logging.INFO)
|
| 622 |
+
|
| 623 |
+
optimizer = SystemOptimizer()
|
| 624 |
+
|
| 625 |
+
# Test profile application
|
| 626 |
+
print("Available profiles:")
|
| 627 |
+
for name, profile in optimizer.profiles.items():
|
| 628 |
+
print(f" {name}: {profile.description}")
|
| 629 |
+
|
| 630 |
+
if optimizer.apply_profile("performance"):
|
| 631 |
+
print("Successfully applied performance profile")
|
| 632 |
+
|
| 633 |
+
# Start monitoring
|
| 634 |
+
optimizer.start_monitoring()
|
| 635 |
+
|
| 636 |
+
try:
|
| 637 |
+
# Collect some data
|
| 638 |
+
time.sleep(10)
|
| 639 |
+
|
| 640 |
+
# Get analytics
|
| 641 |
+
analytics = optimizer.get_performance_analytics(1)
|
| 642 |
+
print(f"Performance analytics: {analytics}")
|
| 643 |
+
|
| 644 |
+
# Get recommendations
|
| 645 |
+
recommendations = optimizer.get_recommendations()
|
| 646 |
+
print(f"Recommendations: {recommendations}")
|
| 647 |
+
|
| 648 |
+
finally:
|
| 649 |
+
optimizer.stop_monitoring()
|