utils_performance_monitor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. #include "utils_performance_monitor.h"
  2. #include "../base/base_logger.h"
  3. #include <algorithm>
  4. #include <sstream>
  5. #include <fstream>
  6. #include <iomanip>
  7. #include <thread>
  8. #include <cmath>
  9. #ifdef _WIN32
  10. #include <windows.h>
  11. #include <psapi.h>
  12. #include <pdh.h>
  13. #pragma comment(lib, "pdh.lib")
  14. #pragma comment(lib, "psapi.lib")
  15. #else
  16. #include <sys/sysinfo.h>
  17. #include <sys/statvfs.h>
  18. #include <unistd.h>
  19. #endif
  20. namespace av {
  21. namespace utils {
  22. using namespace av::base;
  23. // PerformanceMonitor 实现
  24. PerformanceMonitor::PerformanceMonitor(const MonitorConfig& config)
  25. : config_(config)
  26. , initialized_(false)
  27. , running_(false)
  28. , monitoring_(false)
  29. , startTime_(std::chrono::steady_clock::now())
  30. , lastReportTime_(std::chrono::steady_clock::now()) {
  31. }
  32. PerformanceMonitor::~PerformanceMonitor() {
  33. close();
  34. }
  35. ErrorCode PerformanceMonitor::initialize() {
  36. std::lock_guard<std::mutex> lock(configMutex_);
  37. if (initialized_.load()) {
  38. return ErrorCode::SUCCESS;
  39. }
  40. try {
  41. // 初始化基本指标
  42. registerMetric("system.cpu_usage", MetricType::GAUGE, 90.0);
  43. registerMetric("system.memory_usage", MetricType::GAUGE, 85.0);
  44. registerMetric("system.disk_usage", MetricType::GAUGE, 90.0);
  45. registerMetric("performance.frame_rate", MetricType::RATE, 0.0);
  46. registerMetric("performance.latency", MetricType::HISTOGRAM, 100.0);
  47. registerMetric("performance.throughput", MetricType::RATE, 0.0);
  48. startTime_ = std::chrono::steady_clock::now();
  49. lastReportTime_ = startTime_;
  50. initialized_.store(true);
  51. LOG_INFO("Performance monitor initialized successfully");
  52. return ErrorCode::SUCCESS;
  53. } catch (const std::exception& e) {
  54. LOG_ERROR("Failed to initialize performance monitor: {}", e.what());
  55. return ErrorCode::INITIALIZATION_FAILED;
  56. }
  57. }
  58. ErrorCode PerformanceMonitor::start() {
  59. if (!initialized_.load()) {
  60. return ErrorCode::NOT_INITIALIZED;
  61. }
  62. if (running_.load()) {
  63. return ErrorCode::SUCCESS;
  64. }
  65. running_.store(true);
  66. monitoring_.store(config_.enableMonitoring);
  67. LOG_INFO("Performance monitor started");
  68. return ErrorCode::SUCCESS;
  69. }
  70. ErrorCode PerformanceMonitor::stop() {
  71. if (!running_.load()) {
  72. return ErrorCode::SUCCESS;
  73. }
  74. running_.store(false);
  75. monitoring_.store(false);
  76. LOG_INFO("Performance monitor stopped");
  77. return ErrorCode::SUCCESS;
  78. }
  79. ErrorCode PerformanceMonitor::reset() {
  80. std::lock_guard<std::mutex> lock(metricsMutex_);
  81. resetAllStats();
  82. clearAlerts();
  83. startTime_ = std::chrono::steady_clock::now();
  84. lastReportTime_ = startTime_;
  85. LOG_INFO("Performance monitor reset");
  86. return ErrorCode::SUCCESS;
  87. }
  88. ErrorCode PerformanceMonitor::close() {
  89. stop();
  90. std::lock_guard<std::mutex> metricsLock(metricsMutex_);
  91. std::lock_guard<std::mutex> alertsLock(alertsMutex_);
  92. std::lock_guard<std::mutex> configLock(configMutex_);
  93. metrics_.clear();
  94. metricTypes_.clear();
  95. alertThresholds_.clear();
  96. timerStarts_.clear();
  97. historyData_.clear();
  98. activeAlerts_.clear();
  99. initialized_.store(false);
  100. LOG_INFO("Performance monitor closed");
  101. return ErrorCode::SUCCESS;
  102. }
  103. ErrorCode PerformanceMonitor::registerMetric(const std::string& name, MetricType type, double alertThreshold) {
  104. if (name.empty()) {
  105. return ErrorCode::INVALID_PARAMETER;
  106. }
  107. std::lock_guard<std::mutex> lock(metricsMutex_);
  108. if (metrics_.find(name) != metrics_.end()) {
  109. return ErrorCode::ALREADY_EXISTS;
  110. }
  111. PerformanceStats stats;
  112. stats.name = name;
  113. stats.type = type;
  114. stats.startTime = std::chrono::steady_clock::now();
  115. stats.lastUpdateTime = stats.startTime;
  116. metrics_[name] = stats;
  117. metricTypes_[name] = type;
  118. if (alertThreshold > 0.0) {
  119. alertThresholds_[name] = alertThreshold;
  120. }
  121. if (config_.enableLogging) {
  122. LOG_DEBUG("Registered metric: {} (type: {})", name, static_cast<int>(type));
  123. }
  124. return ErrorCode::SUCCESS;
  125. }
  126. ErrorCode PerformanceMonitor::unregisterMetric(const std::string& name) {
  127. std::lock_guard<std::mutex> lock(metricsMutex_);
  128. auto it = metrics_.find(name);
  129. if (it == metrics_.end()) {
  130. return ErrorCode::NOT_FOUND;
  131. }
  132. metrics_.erase(it);
  133. metricTypes_.erase(name);
  134. alertThresholds_.erase(name);
  135. timerStarts_.erase(name);
  136. historyData_.erase(name);
  137. if (config_.enableLogging) {
  138. LOG_DEBUG("Unregistered metric: {}", name);
  139. }
  140. return ErrorCode::SUCCESS;
  141. }
  142. bool PerformanceMonitor::hasMetric(const std::string& name) const {
  143. std::lock_guard<std::mutex> lock(metricsMutex_);
  144. return metrics_.find(name) != metrics_.end();
  145. }
  146. std::vector<std::string> PerformanceMonitor::getMetricNames() const {
  147. std::lock_guard<std::mutex> lock(metricsMutex_);
  148. std::vector<std::string> names;
  149. names.reserve(metrics_.size());
  150. for (const auto& pair : metrics_) {
  151. names.push_back(pair.first);
  152. }
  153. return names;
  154. }
  155. ErrorCode PerformanceMonitor::incrementCounter(const std::string& name, double value) {
  156. if (!monitoring_.load()) {
  157. return ErrorCode::SUCCESS;
  158. }
  159. updateMetric(name, value, true);
  160. return ErrorCode::SUCCESS;
  161. }
  162. ErrorCode PerformanceMonitor::decrementCounter(const std::string& name, double value) {
  163. if (!monitoring_.load()) {
  164. return ErrorCode::SUCCESS;
  165. }
  166. updateMetric(name, -value, true);
  167. return ErrorCode::SUCCESS;
  168. }
  169. ErrorCode PerformanceMonitor::setCounter(const std::string& name, double value) {
  170. if (!monitoring_.load()) {
  171. return ErrorCode::SUCCESS;
  172. }
  173. updateMetric(name, value, false);
  174. return ErrorCode::SUCCESS;
  175. }
  176. double PerformanceMonitor::getCounter(const std::string& name) const {
  177. std::lock_guard<std::mutex> lock(metricsMutex_);
  178. auto it = metrics_.find(name);
  179. if (it != metrics_.end() && it->second.type == MetricType::COUNTER) {
  180. return it->second.value;
  181. }
  182. return 0.0;
  183. }
  184. ErrorCode PerformanceMonitor::setGauge(const std::string& name, double value) {
  185. if (!monitoring_.load()) {
  186. return ErrorCode::SUCCESS;
  187. }
  188. updateMetric(name, value, false);
  189. return ErrorCode::SUCCESS;
  190. }
  191. ErrorCode PerformanceMonitor::updateGauge(const std::string& name, double delta) {
  192. if (!monitoring_.load()) {
  193. return ErrorCode::SUCCESS;
  194. }
  195. updateMetric(name, delta, true);
  196. return ErrorCode::SUCCESS;
  197. }
  198. double PerformanceMonitor::getGauge(const std::string& name) const {
  199. std::lock_guard<std::mutex> lock(metricsMutex_);
  200. auto it = metrics_.find(name);
  201. if (it != metrics_.end() && it->second.type == MetricType::GAUGE) {
  202. return it->second.value;
  203. }
  204. return 0.0;
  205. }
  206. ErrorCode PerformanceMonitor::recordHistogram(const std::string& name, double value) {
  207. if (!monitoring_.load()) {
  208. return ErrorCode::SUCCESS;
  209. }
  210. std::lock_guard<std::mutex> lock(metricsMutex_);
  211. auto it = metrics_.find(name);
  212. if (it != metrics_.end() && it->second.type == MetricType::HISTOGRAM) {
  213. updateHistogram(it->second, value);
  214. checkAlerts(name, value);
  215. if (config_.enableLogging) {
  216. logMetricUpdate(name, value);
  217. }
  218. }
  219. return ErrorCode::SUCCESS;
  220. }
  221. PerformanceStats PerformanceMonitor::getHistogramStats(const std::string& name) const {
  222. std::lock_guard<std::mutex> lock(metricsMutex_);
  223. auto it = metrics_.find(name);
  224. if (it != metrics_.end() && it->second.type == MetricType::HISTOGRAM) {
  225. return it->second;
  226. }
  227. return PerformanceStats();
  228. }
  229. ErrorCode PerformanceMonitor::startTimer(const std::string& name) {
  230. if (!monitoring_.load()) {
  231. return ErrorCode::SUCCESS;
  232. }
  233. std::lock_guard<std::mutex> lock(metricsMutex_);
  234. timerStarts_[name] = std::chrono::steady_clock::now();
  235. return ErrorCode::SUCCESS;
  236. }
  237. ErrorCode PerformanceMonitor::stopTimer(const std::string& name) {
  238. if (!monitoring_.load()) {
  239. return ErrorCode::SUCCESS;
  240. }
  241. std::lock_guard<std::mutex> lock(metricsMutex_);
  242. auto it = timerStarts_.find(name);
  243. if (it != timerStarts_.end()) {
  244. auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
  245. std::chrono::steady_clock::now() - it->second).count() / 1000.0;
  246. timerStarts_.erase(it);
  247. auto metricIt = metrics_.find(name);
  248. if (metricIt != metrics_.end() && metricIt->second.type == MetricType::TIMER) {
  249. updateStatistics(metricIt->second, duration);
  250. checkAlerts(name, duration);
  251. if (config_.enableLogging) {
  252. logMetricUpdate(name, duration);
  253. }
  254. }
  255. }
  256. return ErrorCode::SUCCESS;
  257. }
  258. ErrorCode PerformanceMonitor::recordTimer(const std::string& name, double duration) {
  259. if (!monitoring_.load()) {
  260. return ErrorCode::SUCCESS;
  261. }
  262. updateMetric(name, duration, false);
  263. return ErrorCode::SUCCESS;
  264. }
  265. double PerformanceMonitor::getTimerAverage(const std::string& name) const {
  266. std::lock_guard<std::mutex> lock(metricsMutex_);
  267. auto it = metrics_.find(name);
  268. if (it != metrics_.end() && it->second.type == MetricType::TIMER) {
  269. return it->second.avgValue;
  270. }
  271. return 0.0;
  272. }
  273. ErrorCode PerformanceMonitor::recordRate(const std::string& name, double value) {
  274. if (!monitoring_.load()) {
  275. return ErrorCode::SUCCESS;
  276. }
  277. updateMetric(name, value, true);
  278. return ErrorCode::SUCCESS;
  279. }
  280. double PerformanceMonitor::getRate(const std::string& name) const {
  281. std::lock_guard<std::mutex> lock(metricsMutex_);
  282. auto it = metrics_.find(name);
  283. if (it != metrics_.end() && it->second.type == MetricType::RATE) {
  284. return it->second.rate;
  285. }
  286. return 0.0;
  287. }
  288. PerformanceStats PerformanceMonitor::getStats(const std::string& name) const {
  289. std::lock_guard<std::mutex> lock(metricsMutex_);
  290. auto it = metrics_.find(name);
  291. if (it != metrics_.end()) {
  292. return it->second;
  293. }
  294. return PerformanceStats();
  295. }
  296. std::map<std::string, PerformanceStats> PerformanceMonitor::getAllStats() const {
  297. std::lock_guard<std::mutex> lock(metricsMutex_);
  298. return metrics_;
  299. }
  300. void PerformanceMonitor::resetStats(const std::string& name) {
  301. std::lock_guard<std::mutex> lock(metricsMutex_);
  302. auto it = metrics_.find(name);
  303. if (it != metrics_.end()) {
  304. it->second.value = 0.0;
  305. it->second.minValue = 0.0;
  306. it->second.maxValue = 0.0;
  307. it->second.avgValue = 0.0;
  308. it->second.count = 0;
  309. it->second.totalCount = 0;
  310. it->second.rate = 0.0;
  311. it->second.startTime = std::chrono::steady_clock::now();
  312. it->second.lastUpdateTime = it->second.startTime;
  313. }
  314. }
  315. void PerformanceMonitor::resetAllStats() {
  316. for (const auto& pair : metrics_) {
  317. resetStats(pair.first);
  318. }
  319. }
  320. void PerformanceMonitor::setConfig(const MonitorConfig& config) {
  321. std::lock_guard<std::mutex> lock(configMutex_);
  322. config_ = config;
  323. monitoring_.store(config_.enableMonitoring && running_.load());
  324. }
  325. MonitorConfig PerformanceMonitor::getConfig() const {
  326. std::lock_guard<std::mutex> lock(configMutex_);
  327. return config_;
  328. }
  329. void PerformanceMonitor::enableMonitoring(bool enable) {
  330. std::lock_guard<std::mutex> lock(configMutex_);
  331. config_.enableMonitoring = enable;
  332. monitoring_.store(enable && running_.load());
  333. }
  334. void PerformanceMonitor::enableLogging(bool enable) {
  335. std::lock_guard<std::mutex> lock(configMutex_);
  336. config_.enableLogging = enable;
  337. }
  338. void PerformanceMonitor::enableReporting(bool enable) {
  339. std::lock_guard<std::mutex> lock(configMutex_);
  340. config_.enableReporting = enable;
  341. }
  342. void PerformanceMonitor::setReportInterval(double interval) {
  343. std::lock_guard<std::mutex> lock(configMutex_);
  344. config_.reportInterval = interval;
  345. }
  346. void PerformanceMonitor::setReportCallback(PerformanceReportCallback callback) {
  347. reportCallback_ = callback;
  348. }
  349. void PerformanceMonitor::setAlertCallback(PerformanceAlertCallback callback) {
  350. alertCallback_ = callback;
  351. }
  352. std::string PerformanceMonitor::generateReport() const {
  353. std::lock_guard<std::mutex> lock(metricsMutex_);
  354. std::ostringstream oss;
  355. oss << "Performance Monitor Report\n";
  356. oss << "========================\n";
  357. oss << "Generated at: " << std::chrono::duration_cast<std::chrono::seconds>(
  358. std::chrono::steady_clock::now().time_since_epoch()).count() << "\n";
  359. oss << "Total metrics: " << metrics_.size() << "\n\n";
  360. for (const auto& pair : metrics_) {
  361. const auto& stats = pair.second;
  362. oss << "Metric: " << stats.name << "\n";
  363. oss << " Type: " << static_cast<int>(stats.type) << "\n";
  364. oss << " Current Value: " << std::fixed << std::setprecision(2) << stats.value << "\n";
  365. oss << " Min/Max/Avg: " << stats.minValue << "/" << stats.maxValue << "/" << stats.avgValue << "\n";
  366. oss << " Count: " << stats.count << "\n";
  367. oss << " Rate: " << stats.rate << "/sec\n";
  368. oss << "\n";
  369. }
  370. return oss.str();
  371. }
  372. ErrorCode PerformanceMonitor::exportToFile(const std::string& filename) const {
  373. try {
  374. std::ofstream file(filename);
  375. if (!file.is_open()) {
  376. return ErrorCode::FILE_OPERATION_FAILED;
  377. }
  378. file << generateReport();
  379. file.close();
  380. return ErrorCode::SUCCESS;
  381. } catch (const std::exception& e) {
  382. LOG_ERROR("Failed to export performance report: {}", e.what());
  383. return ErrorCode::FILE_OPERATION_FAILED;
  384. }
  385. }
  386. ErrorCode PerformanceMonitor::exportToJson(const std::string& filename) const {
  387. // JSON导出实现
  388. return ErrorCode::SUCCESS;
  389. }
  390. ErrorCode PerformanceMonitor::exportToCsv(const std::string& filename) const {
  391. // CSV导出实现
  392. return ErrorCode::SUCCESS;
  393. }
  394. void PerformanceMonitor::setAlertThreshold(const std::string& name, double threshold) {
  395. std::lock_guard<std::mutex> lock(metricsMutex_);
  396. alertThresholds_[name] = threshold;
  397. }
  398. std::vector<PerformanceAlert> PerformanceMonitor::getActiveAlerts() const {
  399. std::lock_guard<std::mutex> lock(alertsMutex_);
  400. return activeAlerts_;
  401. }
  402. void PerformanceMonitor::clearAlerts() {
  403. std::lock_guard<std::mutex> lock(alertsMutex_);
  404. activeAlerts_.clear();
  405. }
  406. // 私有方法实现
  407. void PerformanceMonitor::updateMetric(const std::string& name, double value, bool isIncrement) {
  408. std::lock_guard<std::mutex> lock(metricsMutex_);
  409. auto it = metrics_.find(name);
  410. if (it != metrics_.end()) {
  411. if (isIncrement) {
  412. it->second.value += value;
  413. } else {
  414. it->second.value = value;
  415. }
  416. updateStatistics(it->second, value);
  417. checkAlerts(name, it->second.value);
  418. if (config_.enableLogging) {
  419. logMetricUpdate(name, it->second.value);
  420. }
  421. }
  422. }
  423. void PerformanceMonitor::checkAlerts(const std::string& name, double value) {
  424. if (!config_.enableAlerts) {
  425. return;
  426. }
  427. auto thresholdIt = alertThresholds_.find(name);
  428. if (thresholdIt != alertThresholds_.end() && value > thresholdIt->second) {
  429. PerformanceAlert alert;
  430. alert.metricName = name;
  431. alert.currentValue = value;
  432. alert.threshold = thresholdIt->second;
  433. alert.message = "Metric " + name + " exceeded threshold";
  434. alert.timestamp = std::chrono::steady_clock::now();
  435. {
  436. std::lock_guard<std::mutex> alertLock(alertsMutex_);
  437. activeAlerts_.push_back(alert);
  438. }
  439. if (alertCallback_) {
  440. alertCallback_(alert);
  441. }
  442. }
  443. }
  444. void PerformanceMonitor::logMetricUpdate(const std::string& name, double value) {
  445. LOG_DEBUG("Metric updated: {} = {}", name, value);
  446. }
  447. void PerformanceMonitor::updateStatistics(PerformanceStats& stats, double value) {
  448. stats.count++;
  449. stats.totalCount++;
  450. stats.lastUpdateTime = std::chrono::steady_clock::now();
  451. if (stats.count == 1) {
  452. stats.minValue = value;
  453. stats.maxValue = value;
  454. stats.avgValue = value;
  455. } else {
  456. stats.minValue = std::min(stats.minValue, value);
  457. stats.maxValue = std::max(stats.maxValue, value);
  458. stats.avgValue = (stats.avgValue * (stats.count - 1) + value) / stats.count;
  459. }
  460. // 计算速率
  461. if (stats.type == MetricType::RATE) {
  462. auto duration = std::chrono::duration_cast<std::chrono::seconds>(
  463. stats.lastUpdateTime - stats.startTime).count();
  464. if (duration > 0) {
  465. stats.rate = stats.totalCount / static_cast<double>(duration);
  466. }
  467. }
  468. }
  469. void PerformanceMonitor::updateHistogram(PerformanceStats& stats, double value) {
  470. updateStatistics(stats, value);
  471. // 保存历史数据
  472. auto& history = historyData_[stats.name];
  473. history.push_back(value);
  474. if (history.size() > config_.maxHistorySize) {
  475. history.erase(history.begin());
  476. }
  477. }
  478. // ScopedTimer 实现
  479. ScopedTimer::ScopedTimer(PerformanceMonitor* monitor, const std::string& name)
  480. : monitor_(monitor)
  481. , name_(name)
  482. , startTime_(std::chrono::steady_clock::now()) {
  483. }
  484. ScopedTimer::~ScopedTimer() {
  485. if (monitor_) {
  486. auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
  487. std::chrono::steady_clock::now() - startTime_).count() / 1000.0;
  488. monitor_->recordTimer(name_, duration);
  489. }
  490. }
  491. // SystemPerformanceMonitor 实现
  492. SystemPerformanceMonitor::SystemPerformanceMonitor()
  493. : cpuUsage_(0.0)
  494. , memoryUsage_(0.0)
  495. , diskUsage_(0.0)
  496. , networkUsage_(0.0)
  497. , gpuUsage_(0.0)
  498. , lastUpdateTime_(std::chrono::steady_clock::now()) {
  499. }
  500. SystemPerformanceMonitor::~SystemPerformanceMonitor() {
  501. }
  502. ErrorCode SystemPerformanceMonitor::collectCpuUsage() {
  503. #ifdef _WIN32
  504. // Windows CPU使用率收集实现
  505. static PDH_HQUERY cpuQuery;
  506. static PDH_HCOUNTER cpuTotal;
  507. static bool initialized = false;
  508. if (!initialized) {
  509. PdhOpenQuery(NULL, NULL, &cpuQuery);
  510. PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
  511. PdhCollectQueryData(cpuQuery);
  512. initialized = true;
  513. }
  514. PDH_FMT_COUNTERVALUE counterVal;
  515. PdhCollectQueryData(cpuQuery);
  516. PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
  517. cpuUsage_.store(counterVal.doubleValue);
  518. #else
  519. // Linux CPU使用率收集实现
  520. cpuUsage_.store(0.0); // 简化实现
  521. #endif
  522. return ErrorCode::SUCCESS;
  523. }
  524. ErrorCode SystemPerformanceMonitor::collectMemoryUsage() {
  525. #ifdef _WIN32
  526. MEMORYSTATUSEX memInfo;
  527. memInfo.dwLength = sizeof(MEMORYSTATUSEX);
  528. GlobalMemoryStatusEx(&memInfo);
  529. double totalMem = static_cast<double>(memInfo.ullTotalPhys);
  530. double availMem = static_cast<double>(memInfo.ullAvailPhys);
  531. double usedMem = totalMem - availMem;
  532. memoryUsage_.store((usedMem / totalMem) * 100.0);
  533. #else
  534. struct sysinfo memInfo;
  535. sysinfo(&memInfo);
  536. double totalMem = static_cast<double>(memInfo.totalram * memInfo.mem_unit);
  537. double freeMem = static_cast<double>(memInfo.freeram * memInfo.mem_unit);
  538. double usedMem = totalMem - freeMem;
  539. memoryUsage_.store((usedMem / totalMem) * 100.0);
  540. #endif
  541. return ErrorCode::SUCCESS;
  542. }
  543. ErrorCode SystemPerformanceMonitor::collectDiskUsage() {
  544. // 磁盘使用率收集实现
  545. diskUsage_.store(0.0); // 简化实现
  546. return ErrorCode::SUCCESS;
  547. }
  548. ErrorCode SystemPerformanceMonitor::collectNetworkUsage() {
  549. // 网络使用率收集实现
  550. networkUsage_.store(0.0); // 简化实现
  551. return ErrorCode::SUCCESS;
  552. }
  553. ErrorCode SystemPerformanceMonitor::collectGpuUsage() {
  554. // GPU使用率收集实现
  555. gpuUsage_.store(0.0); // 简化实现
  556. return ErrorCode::SUCCESS;
  557. }
  558. double SystemPerformanceMonitor::getCpuUsage() const {
  559. return cpuUsage_.load();
  560. }
  561. double SystemPerformanceMonitor::getMemoryUsage() const {
  562. return memoryUsage_.load();
  563. }
  564. double SystemPerformanceMonitor::getDiskUsage() const {
  565. return diskUsage_.load();
  566. }
  567. double SystemPerformanceMonitor::getNetworkUsage() const {
  568. return networkUsage_.load();
  569. }
  570. double SystemPerformanceMonitor::getGpuUsage() const {
  571. return gpuUsage_.load();
  572. }
  573. std::string SystemPerformanceMonitor::getSystemInfo() const {
  574. std::ostringstream oss;
  575. oss << "System Performance:\n";
  576. oss << "CPU Usage: " << std::fixed << std::setprecision(1) << getCpuUsage() << "%\n";
  577. oss << "Memory Usage: " << getMemoryUsage() << "%\n";
  578. oss << "Disk Usage: " << getDiskUsage() << "%\n";
  579. oss << "Network Usage: " << getNetworkUsage() << "%\n";
  580. oss << "GPU Usage: " << getGpuUsage() << "%\n";
  581. return oss.str();
  582. }
  583. std::string SystemPerformanceMonitor::getCpuInfo() const {
  584. return "CPU Information"; // 简化实现
  585. }
  586. std::string SystemPerformanceMonitor::getMemoryInfo() const {
  587. return "Memory Information"; // 简化实现
  588. }
  589. std::string SystemPerformanceMonitor::getGpuInfo() const {
  590. return "GPU Information"; // 简化实现
  591. }
  592. ErrorCode SystemPerformanceMonitor::integrateWithMonitor(PerformanceMonitor* monitor) {
  593. if (!monitor) {
  594. return ErrorCode::INVALID_PARAMETER;
  595. }
  596. // 定期更新系统指标到性能监控器
  597. collectCpuUsage();
  598. collectMemoryUsage();
  599. collectDiskUsage();
  600. collectNetworkUsage();
  601. collectGpuUsage();
  602. monitor->setGauge("system.cpu_usage", getCpuUsage());
  603. monitor->setGauge("system.memory_usage", getMemoryUsage());
  604. monitor->setGauge("system.disk_usage", getDiskUsage());
  605. monitor->setGauge("system.network_usage", getNetworkUsage());
  606. monitor->setGauge("system.gpu_usage", getGpuUsage());
  607. return ErrorCode::SUCCESS;
  608. }
  609. void SystemPerformanceMonitor::updateSystemMetrics() {
  610. collectCpuUsage();
  611. collectMemoryUsage();
  612. collectDiskUsage();
  613. collectNetworkUsage();
  614. collectGpuUsage();
  615. lastUpdateTime_ = std::chrono::steady_clock::now();
  616. }
  617. // PerformanceMonitorFactory 实现
  618. std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createStandardMonitor() {
  619. MonitorConfig config;
  620. config.enableMonitoring = true;
  621. config.enableLogging = true;
  622. config.enableReporting = true;
  623. config.reportInterval = 10.0;
  624. config.maxHistorySize = 1000;
  625. config.enableAlerts = true;
  626. return std::make_unique<PerformanceMonitor>(config);
  627. }
  628. std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createLightweightMonitor() {
  629. MonitorConfig config;
  630. config.enableMonitoring = true;
  631. config.enableLogging = false;
  632. config.enableReporting = false;
  633. config.reportInterval = 60.0;
  634. config.maxHistorySize = 100;
  635. config.enableAlerts = false;
  636. return std::make_unique<PerformanceMonitor>(config);
  637. }
  638. std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createDetailedMonitor() {
  639. MonitorConfig config;
  640. config.enableMonitoring = true;
  641. config.enableLogging = true;
  642. config.enableReporting = true;
  643. config.reportInterval = 5.0;
  644. config.maxHistorySize = 5000;
  645. config.enableAlerts = true;
  646. return std::make_unique<PerformanceMonitor>(config);
  647. }
  648. std::unique_ptr<PerformanceMonitor> PerformanceMonitorFactory::createRealtimeMonitor() {
  649. MonitorConfig config;
  650. config.enableMonitoring = true;
  651. config.enableLogging = false;
  652. config.enableReporting = true;
  653. config.reportInterval = 1.0;
  654. config.maxHistorySize = 500;
  655. config.enableAlerts = true;
  656. return std::make_unique<PerformanceMonitor>(config);
  657. }
  658. std::unique_ptr<SystemPerformanceMonitor> PerformanceMonitorFactory::createSystemMonitor() {
  659. return std::make_unique<SystemPerformanceMonitor>();
  660. }
  661. } // namespace utils
  662. } // namespace av