答案:通过平台特定API获取CPU和内存使用率,windows使用PDH和GlobalMemoryStatusEx,linux读取/proc/stat和/proc/meminfo,跨平台可封装统一接口实现资源监控。

在c++中获取系统CPU和内存使用情况,需要根据操作系统选择不同的实现方式。windows和Linux系统提供了各自的API或文件接口来监控系统资源。以下是跨平台的实现思路与具体代码示例。
Windows平台获取CPU和内存使用
windows系统可通过调用Performance Data Helper (PDH) API 或 GetSystemInfo、GlobalMemoryStatusEx 等函数获取资源信息。
CPU使用率: 使用PDH库可以方便地读取CPU利用率。
示例代码:
#include <windows.h> #include <pdh.h> #pragma comment(lib, "pdh.lib") <p>double GetCPULoad() { static PDH_HQUERY query = NULL; static PDH_HCOUNTER counter = NULL; if (!query) { PdhOpenQuery(NULL, 0, &query); PdhAddCounter(query, L"Processor(_Total)% Processor Time", 0, &counter); PdhCollectQueryData(query); } PdhCollectQueryData(query); PDH_FMT_COUNTERVALUE value; PdhGetFormattedCounterValue(counter, PDH_FMT_DOUBLE, NULL, &value); return value.doubleValue; }
内存使用: 使用 GlobalMemoryStatusEx 获取总内存和已用内存。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <windows.h> <p>void GetMemoryUsage(DwordLONG& total, DWORDLONG& used) { MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(memInfo); GlobalMemoryStatusEx(&memInfo); total = memInfo.ullTotalPhys / (1024 <em> 1024); // 单位:MB used = (memInfo.ullTotalPhys - memInfo.ullAvailPhys) / (1024 </em> 1024); }
Linux平台获取CPU和内存使用
Linux系统通过读取 /proc/stat 和 /proc/meminfo 文件获取CPU和内存数据。
CPU使用率: 解析 /proc/stat 中第一行(cpu总和),计算空闲时间变化率。
示例代码:
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <unistd.h> <p>struct CpuTimes { unsigned long long user, nice, system, idle, iowait, irq, softirq; };</p><p>CpuTimes GetCpuTimes() { std::ifstream file("/proc/stat"); std::string line; std::getline(file, line); std::istringstream ss(line); std::string cpu; CpuTimes times; ss >> cpu >> times.user >> times.nice >> times.system >> times.idle >> times.iowait >> times.irq >> times.softirq; return times; }</p><p>double CalculateCPULoad() { auto start = GetCpuTimes(); sleep(1); auto end = GetCpuTimes();</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">auto idle = end.idle - start.idle; auto total = (end.user + end.nice + end.system + end.idle + end.iowait + end.irq + end.softirq) - (start.user + start.nice + start.system + start.idle + start.iowait + start.irq + start.softirq); return 100.0 * (total - idle) / total;
}
内存使用: 读取 /proc/meminfo 中的MemTotal和MemAvailable字段。
示例代码:
void GetMemoryUsage(long& totalMB, long& usedMB) { std::ifstream file("/proc/meminfo"); std::string line; long total = 0, free = 0; <pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">while (std::getline(file, line)) { if (line.find("MemTotal") == 0) { std::sscanf(line.c_str(), "MemTotal: %ld kB", &total); } else if (line.find("MemAvailable") == 0) { std::sscanf(line.c_str(), "MemAvailable: %ld kB", &free); break; } } totalMB = total / 1024; usedMB = (total - free) / 1024;
}
跨平台封装建议
为便于在不同系统使用,可定义统一接口:
struct SystemResource { double cpuLoad; // 百分比 long memoryUsed; // MB long memoryTotal; }; <p>SystemResource GetSystemResource() { SystemResource res = {0};</p><h1>ifdef _WIN32</h1><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">res.cpuLoad = GetCPULoad(); GetMemoryUsage(res.memoryTotal, res.memoryUsed);
else
res.cpuLoad = CalculateCPULoad(); // 注意:此版本需等待1秒 GetMemoryUsage(res.memoryTotal, res.memoryUsed);
endif
return res;
}
若需非阻塞CPU采样,可保存上一次时间戳和CPU时间,做增量计算。
注意事项
Linux下CPU使用率需两次采样,不能单次读取获得;Windows PDH方式更实时。内存数据可直接获取。生产环境中建议将采集逻辑放入独立线程,并控制采样频率(如每秒一次)以减少开销。
基本上就这些。根据不同系统选择合适方法,结构清晰即可稳定监控资源。


