utils_performance_monitor.cpp 24 KB

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