#include "utils_performance_monitor.h" #include "../base/logger.h" #include #include #include #include #include #include #include #ifdef _WIN32 #include #include #include #pragma comment(lib, "pdh.lib") #pragma comment(lib, "psapi.lib") #else #include #include #include #endif namespace av { namespace utils { using namespace av; // PerformanceMonitor 实现 PerformanceMonitor::PerformanceMonitor(const MonitorConfig& config) : config_(config) , initialized_(false) , running_(false) , monitoring_(false) , startTime_(std::chrono::steady_clock::now()) , lastReportTime_(std::chrono::steady_clock::now()) { } PerformanceMonitor::~PerformanceMonitor() { close(); } ErrorCode PerformanceMonitor::initialize() { std::lock_guard lock(configMutex_); if (initialized_.load()) { return ErrorCode::SUCCESS; } try { // 初始化基本指标 registerMetric("system.cpu_usage", MetricType::GAUGE, 90.0); registerMetric("system.memory_usage", MetricType::GAUGE, 85.0); registerMetric("system.disk_usage", MetricType::GAUGE, 90.0); registerMetric("performance.frame_rate", MetricType::RATE, 0.0); registerMetric("performance.latency", MetricType::HISTOGRAM, 100.0); registerMetric("performance.throughput", MetricType::RATE, 0.0); startTime_ = std::chrono::steady_clock::now(); lastReportTime_ = startTime_; initialized_.store(true); Logger::instance().info("Performance monitor initialized successfully"); return ErrorCode::SUCCESS; } catch (const std::exception& e) { Logger::instance().errorf("Failed to initialize performance monitor: {}", e.what()); return ErrorCode::INITIALIZATION_FAILED; } } ErrorCode PerformanceMonitor::start() { if (!initialized_.load()) { return ErrorCode::NOT_INITIALIZED; } if (running_.load()) { return ErrorCode::SUCCESS; } running_.store(true); monitoring_.store(config_.enableMonitoring); Logger::instance().info("Performance monitor started"); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::stop() { if (!running_.load()) { return ErrorCode::SUCCESS; } running_.store(false); monitoring_.store(false); Logger::instance().info("Performance monitor stopped"); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::reset() { std::lock_guard lock(metricsMutex_); resetAllStats(); clearAlerts(); startTime_ = std::chrono::steady_clock::now(); lastReportTime_ = startTime_; Logger::instance().info("Performance monitor reset"); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::close() { stop(); std::lock_guard metricsLock(metricsMutex_); std::lock_guard alertsLock(alertsMutex_); std::lock_guard configLock(configMutex_); metrics_.clear(); metricTypes_.clear(); alertThresholds_.clear(); timerStarts_.clear(); historyData_.clear(); activeAlerts_.clear(); initialized_.store(false); Logger::instance().info("Performance monitor closed"); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::registerMetric(const std::string& name, MetricType type, double alertThreshold) { if (name.empty()) { return ErrorCode::INVALID_PARAMS; } std::lock_guard lock(metricsMutex_); if (metrics_.find(name) != metrics_.end()) { return ErrorCode::ALREADY_EXISTS; } PerformanceStats stats; stats.name = name; stats.type = type; stats.startTime = std::chrono::steady_clock::now(); stats.lastUpdateTime = stats.startTime; metrics_[name] = stats; metricTypes_[name] = type; if (alertThreshold > 0.0) { alertThresholds_[name] = alertThreshold; } if (config_.enableLogging) { Logger::instance().debugf("Registered metric: {} (type: {})", name, static_cast(type)); } return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::unregisterMetric(const std::string& name) { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it == metrics_.end()) { return ErrorCode::NOT_FOUND; } metrics_.erase(it); metricTypes_.erase(name); alertThresholds_.erase(name); timerStarts_.erase(name); historyData_.erase(name); if (config_.enableLogging) { Logger::instance().debugf("Unregistered metric: {}", name); } return ErrorCode::SUCCESS; } bool PerformanceMonitor::hasMetric(const std::string& name) const { std::lock_guard lock(metricsMutex_); return metrics_.find(name) != metrics_.end(); } std::vector PerformanceMonitor::getMetricNames() const { std::lock_guard lock(metricsMutex_); std::vector names; names.reserve(metrics_.size()); for (const auto& pair : metrics_) { names.push_back(pair.first); } return names; } ErrorCode PerformanceMonitor::incrementCounter(const std::string& name, double value) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, value, true); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::decrementCounter(const std::string& name, double value) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, -value, true); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::setCounter(const std::string& name, double value) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, value, false); return ErrorCode::SUCCESS; } double PerformanceMonitor::getCounter(const std::string& name) const { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end() && it->second.type == MetricType::COUNTER) { return it->second.value; } return 0.0; } ErrorCode PerformanceMonitor::setGauge(const std::string& name, double value) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, value, false); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::updateGauge(const std::string& name, double delta) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, delta, true); return ErrorCode::SUCCESS; } double PerformanceMonitor::getGauge(const std::string& name) const { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end() && it->second.type == MetricType::GAUGE) { return it->second.value; } return 0.0; } ErrorCode PerformanceMonitor::recordHistogram(const std::string& name, double value) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end() && it->second.type == MetricType::HISTOGRAM) { updateHistogram(it->second, value); checkAlerts(name, value); if (config_.enableLogging) { logMetricUpdate(name, value); } } return ErrorCode::SUCCESS; } PerformanceStats PerformanceMonitor::getHistogramStats(const std::string& name) const { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end() && it->second.type == MetricType::HISTOGRAM) { return it->second; } return PerformanceStats(); } ErrorCode PerformanceMonitor::startTimer(const std::string& name) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } std::lock_guard lock(metricsMutex_); timerStarts_[name] = std::chrono::steady_clock::now(); return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::stopTimer(const std::string& name) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } std::lock_guard lock(metricsMutex_); auto it = timerStarts_.find(name); if (it != timerStarts_.end()) { auto duration = std::chrono::duration_cast( std::chrono::steady_clock::now() - it->second).count() / 1000.0; timerStarts_.erase(it); auto metricIt = metrics_.find(name); if (metricIt != metrics_.end() && metricIt->second.type == MetricType::TIMER) { updateStatistics(metricIt->second, duration); checkAlerts(name, duration); if (config_.enableLogging) { logMetricUpdate(name, duration); } } } return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::recordTimer(const std::string& name, double duration) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, duration, false); return ErrorCode::SUCCESS; } double PerformanceMonitor::getTimerAverage(const std::string& name) const { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end() && it->second.type == MetricType::TIMER) { return it->second.avgValue; } return 0.0; } ErrorCode PerformanceMonitor::recordRate(const std::string& name, double value) { if (!monitoring_.load()) { return ErrorCode::SUCCESS; } updateMetric(name, value, true); return ErrorCode::SUCCESS; } double PerformanceMonitor::getRate(const std::string& name) const { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end() && it->second.type == MetricType::RATE) { return it->second.rate; } return 0.0; } PerformanceStats PerformanceMonitor::getStats(const std::string& name) const { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end()) { return it->second; } return PerformanceStats(); } std::map PerformanceMonitor::getAllStats() const { std::lock_guard lock(metricsMutex_); return metrics_; } void PerformanceMonitor::resetStats(const std::string& name) { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end()) { it->second.value = 0.0; it->second.minValue = 0.0; it->second.maxValue = 0.0; it->second.avgValue = 0.0; it->second.count = 0; it->second.totalCount = 0; it->second.rate = 0.0; it->second.startTime = std::chrono::steady_clock::now(); it->second.lastUpdateTime = it->second.startTime; } } void PerformanceMonitor::resetAllStats() { for (const auto& pair : metrics_) { resetStats(pair.first); } } void PerformanceMonitor::setConfig(const MonitorConfig& config) { std::lock_guard lock(configMutex_); config_ = config; monitoring_.store(config_.enableMonitoring && running_.load()); } MonitorConfig PerformanceMonitor::getConfig() const { std::lock_guard lock(configMutex_); return config_; } void PerformanceMonitor::enableMonitoring(bool enable) { std::lock_guard lock(configMutex_); config_.enableMonitoring = enable; monitoring_.store(enable && running_.load()); } void PerformanceMonitor::enableLogging(bool enable) { std::lock_guard lock(configMutex_); config_.enableLogging = enable; } void PerformanceMonitor::enableReporting(bool enable) { std::lock_guard lock(configMutex_); config_.enableReporting = enable; } void PerformanceMonitor::setReportInterval(double interval) { std::lock_guard lock(configMutex_); config_.reportInterval = interval; } void PerformanceMonitor::setReportCallback(PerformanceReportCallback callback) { reportCallback_ = callback; } void PerformanceMonitor::setAlertCallback(PerformanceAlertCallback callback) { alertCallback_ = callback; } std::string PerformanceMonitor::generateReport() const { std::lock_guard lock(metricsMutex_); std::ostringstream oss; oss << "Performance Monitor Report\n"; oss << "========================\n"; oss << "Generated at: " << std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()).count() << "\n"; oss << "Total metrics: " << metrics_.size() << "\n\n"; for (const auto& pair : metrics_) { const auto& stats = pair.second; oss << "Metric: " << stats.name << "\n"; oss << " Type: " << static_cast(stats.type) << "\n"; oss << " Current Value: " << std::fixed << std::setprecision(2) << stats.value << "\n"; oss << " Min/Max/Avg: " << stats.minValue << "/" << stats.maxValue << "/" << stats.avgValue << "\n"; oss << " Count: " << stats.count << "\n"; oss << " Rate: " << stats.rate << "/sec\n"; oss << "\n"; } return oss.str(); } ErrorCode PerformanceMonitor::exportToFile(const std::string& filename) const { try { std::ofstream file(filename); if (!file.is_open()) { return ErrorCode::FILE_OPERATION_FAILED; } file << generateReport(); file.close(); return ErrorCode::SUCCESS; } catch (const std::exception& e) { Logger::instance().errorf("Failed to export performance report: {}", e.what()); return ErrorCode::FILE_OPERATION_FAILED; } } ErrorCode PerformanceMonitor::exportToJson(const std::string& filename) const { // JSON导出实现 return ErrorCode::SUCCESS; } ErrorCode PerformanceMonitor::exportToCsv(const std::string& filename) const { // CSV导出实现 return ErrorCode::SUCCESS; } void PerformanceMonitor::setAlertThreshold(const std::string& name, double threshold) { std::lock_guard lock(metricsMutex_); alertThresholds_[name] = threshold; } std::vector PerformanceMonitor::getActiveAlerts() const { std::lock_guard lock(alertsMutex_); return activeAlerts_; } void PerformanceMonitor::clearAlerts() { std::lock_guard lock(alertsMutex_); activeAlerts_.clear(); } // 私有方法实现 void PerformanceMonitor::updateMetric(const std::string& name, double value, bool isIncrement) { std::lock_guard lock(metricsMutex_); auto it = metrics_.find(name); if (it != metrics_.end()) { if (isIncrement) { it->second.value += value; } else { it->second.value = value; } updateStatistics(it->second, value); checkAlerts(name, it->second.value); if (config_.enableLogging) { logMetricUpdate(name, it->second.value); } } } void PerformanceMonitor::checkAlerts(const std::string& name, double value) { if (!config_.enableAlerts) { return; } auto thresholdIt = alertThresholds_.find(name); if (thresholdIt != alertThresholds_.end() && value > thresholdIt->second) { PerformanceAlert alert; alert.metricName = name; alert.currentValue = value; alert.threshold = thresholdIt->second; alert.message = "Metric " + name + " exceeded threshold"; alert.timestamp = std::chrono::steady_clock::now(); { std::lock_guard alertLock(alertsMutex_); activeAlerts_.push_back(alert); } if (alertCallback_) { alertCallback_(alert); } } } void PerformanceMonitor::logMetricUpdate(const std::string& name, double value) { Logger::instance().debugf("Metric updated: {} = {}", name, value); } void PerformanceMonitor::updateStatistics(PerformanceStats& stats, double value) { stats.count++; stats.totalCount++; stats.lastUpdateTime = std::chrono::steady_clock::now(); if (stats.count == 1) { stats.minValue = value; stats.maxValue = value; stats.avgValue = value; } else { stats.minValue = (std::min)(stats.minValue, value); stats.maxValue = (std::max)(stats.maxValue, value); stats.avgValue = (stats.avgValue * (stats.count - 1) + value) / stats.count; } // 计算速率 if (stats.type == MetricType::RATE) { auto duration = std::chrono::duration_cast( stats.lastUpdateTime - stats.startTime).count(); if (duration > 0) { stats.rate = stats.totalCount / static_cast(duration); } } } void PerformanceMonitor::updateHistogram(PerformanceStats& stats, double value) { updateStatistics(stats, value); // 保存历史数据 auto& history = historyData_[stats.name]; history.push_back(value); if (history.size() > config_.maxHistorySize) { history.erase(history.begin()); } } // ScopedTimer 实现 ScopedTimer::ScopedTimer(PerformanceMonitor* monitor, const std::string& name) : monitor_(monitor) , name_(name) , startTime_(std::chrono::steady_clock::now()) { } ScopedTimer::~ScopedTimer() { if (monitor_) { auto duration = std::chrono::duration_cast( std::chrono::steady_clock::now() - startTime_).count() / 1000.0; monitor_->recordTimer(name_, duration); } } // SystemPerformanceMonitor 实现 SystemPerformanceMonitor::SystemPerformanceMonitor() : cpuUsage_(0.0) , memoryUsage_(0.0) , diskUsage_(0.0) , networkUsage_(0.0) , gpuUsage_(0.0) , lastUpdateTime_(std::chrono::steady_clock::now()) { } SystemPerformanceMonitor::~SystemPerformanceMonitor() { } ErrorCode SystemPerformanceMonitor::collectCpuUsage() { #ifdef _WIN32 // Windows CPU使用率收集实现 static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; static bool initialized = false; if (!initialized) { PdhOpenQuery(NULL, NULL, &cpuQuery); PdhAddEnglishCounterA(cpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal); PdhCollectQueryData(cpuQuery); initialized = true; } PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData(cpuQuery); PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal); cpuUsage_.store(counterVal.doubleValue); #else // Linux CPU使用率收集实现 cpuUsage_.store(0.0); // 简化实现 #endif return ErrorCode::SUCCESS; } ErrorCode SystemPerformanceMonitor::collectMemoryUsage() { #ifdef _WIN32 MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); double totalMem = static_cast(memInfo.ullTotalPhys); double availMem = static_cast(memInfo.ullAvailPhys); double usedMem = totalMem - availMem; memoryUsage_.store((usedMem / totalMem) * 100.0); #else struct sysinfo memInfo; sysinfo(&memInfo); double totalMem = static_cast(memInfo.totalram * memInfo.mem_unit); double freeMem = static_cast(memInfo.freeram * memInfo.mem_unit); double usedMem = totalMem - freeMem; memoryUsage_.store((usedMem / totalMem) * 100.0); #endif return ErrorCode::SUCCESS; } ErrorCode SystemPerformanceMonitor::collectDiskUsage() { // 磁盘使用率收集实现 diskUsage_.store(0.0); // 简化实现 return ErrorCode::SUCCESS; } ErrorCode SystemPerformanceMonitor::collectNetworkUsage() { // 网络使用率收集实现 networkUsage_.store(0.0); // 简化实现 return ErrorCode::SUCCESS; } ErrorCode SystemPerformanceMonitor::collectGpuUsage() { // GPU使用率收集实现 gpuUsage_.store(0.0); // 简化实现 return ErrorCode::SUCCESS; } double SystemPerformanceMonitor::getCpuUsage() const { return cpuUsage_.load(); } double SystemPerformanceMonitor::getMemoryUsage() const { return memoryUsage_.load(); } double SystemPerformanceMonitor::getDiskUsage() const { return diskUsage_.load(); } double SystemPerformanceMonitor::getNetworkUsage() const { return networkUsage_.load(); } double SystemPerformanceMonitor::getGpuUsage() const { return gpuUsage_.load(); } std::string SystemPerformanceMonitor::getSystemInfo() const { std::ostringstream oss; oss << "System Performance:\n"; oss << "CPU Usage: " << std::fixed << std::setprecision(1) << getCpuUsage() << "%\n"; oss << "Memory Usage: " << getMemoryUsage() << "%\n"; oss << "Disk Usage: " << getDiskUsage() << "%\n"; oss << "Network Usage: " << getNetworkUsage() << "%\n"; oss << "GPU Usage: " << getGpuUsage() << "%\n"; return oss.str(); } std::string SystemPerformanceMonitor::getCpuInfo() const { return "CPU Information"; // 简化实现 } std::string SystemPerformanceMonitor::getMemoryInfo() const { return "Memory Information"; // 简化实现 } std::string SystemPerformanceMonitor::getGpuInfo() const { return "GPU Information"; // 简化实现 } ErrorCode SystemPerformanceMonitor::integrateWithMonitor(PerformanceMonitor* monitor) { if (!monitor) { return ErrorCode::INVALID_PARAMS; } // 定期更新系统指标到性能监控器 collectCpuUsage(); collectMemoryUsage(); collectDiskUsage(); collectNetworkUsage(); collectGpuUsage(); monitor->setGauge("system.cpu_usage", getCpuUsage()); monitor->setGauge("system.memory_usage", getMemoryUsage()); monitor->setGauge("system.disk_usage", getDiskUsage()); monitor->setGauge("system.network_usage", getNetworkUsage()); monitor->setGauge("system.gpu_usage", getGpuUsage()); return ErrorCode::SUCCESS; } void SystemPerformanceMonitor::updateSystemMetrics() { collectCpuUsage(); collectMemoryUsage(); collectDiskUsage(); collectNetworkUsage(); collectGpuUsage(); lastUpdateTime_ = std::chrono::steady_clock::now(); } // PerformanceMonitorFactory 实现 std::unique_ptr PerformanceMonitorFactory::createStandardMonitor() { MonitorConfig config; config.enableMonitoring = true; config.enableLogging = true; config.enableReporting = true; config.reportInterval = 10.0; config.maxHistorySize = 1000; config.enableAlerts = true; return std::make_unique(config); } std::unique_ptr PerformanceMonitorFactory::createLightweightMonitor() { MonitorConfig config; config.enableMonitoring = true; config.enableLogging = false; config.enableReporting = false; config.reportInterval = 60.0; config.maxHistorySize = 100; config.enableAlerts = false; return std::make_unique(config); } std::unique_ptr PerformanceMonitorFactory::createDetailedMonitor() { MonitorConfig config; config.enableMonitoring = true; config.enableLogging = true; config.enableReporting = true; config.reportInterval = 5.0; config.maxHistorySize = 5000; config.enableAlerts = true; return std::make_unique(config); } std::unique_ptr PerformanceMonitorFactory::createRealtimeMonitor() { MonitorConfig config; config.enableMonitoring = true; config.enableLogging = false; config.enableReporting = true; config.reportInterval = 1.0; config.maxHistorySize = 500; config.enableAlerts = true; return std::make_unique(config); } std::unique_ptr PerformanceMonitorFactory::createSystemMonitor() { return std::make_unique(); } } // namespace utils } // namespace av