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

在C++中获取系统CPU和内存使用情况,需要根据操作系统选择不同的实现方式。Windows和Linux系统提供了各自的API或文件接口来监控系统资源。以下是跨平台的实现思路与具体代码示例。
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);
}
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);res.cpuLoad = CalculateCPULoad(); // 注意:此版本需等待1秒 GetMemoryUsage(res.memoryTotal, res.memoryUsed);
return res;
}
若需非阻塞CPU采样,可保存上一次时间戳和CPU时间,做增量计算。
Linux下CPU使用率需两次采样,不能单次读取获得;Windows PDH方式更实时。内存数据可直接获取。生产环境中建议将采集逻辑放入独立线程,并控制采样频率(如每秒一次)以减少开销。
基本上就这些。根据不同系统选择合适方法,结构清晰即可稳定监控资源。
以上就是c++++如何获取系统CPU和内存使用情况_c++系统资源监控实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号