一、准备环境
二、新建 VS2022 项目
三、检测 CPU 信息
在 Windows 下,可以通过 GetSystemInfo() 和 __cpuid 指令获取 CPU 的厂商、型号和核心数。
示例代码:获取 CPU 信息
#include <iostream>
#include <windows.h>
#include <intrin.h>
void GetCPUInfo() {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
// CPU 内核数
std::cout << "CPU 核心数: " << sysInfo.dwNumberOfProcessors << std::endl;
// 获取 CPU 厂商信息
int cpuInfo[4] = { -1 };
char cpuBrand[0x40];
__cpuid(cpuInfo, 0x80000002);
memcpy(cpuBrand, cpuInfo, sizeof(cpuInfo));
__cpuid(cpuInfo, 0x80000003);
memcpy(cpuBrand + 16, cpuInfo, sizeof(cpuInfo));
__cpuid(cpuInfo, 0x80000004);
memcpy(cpuBrand + 32, cpuInfo, sizeof(cpuInfo));
std::cout << "CPU 型号: " << cpuBrand << std::endl;
}
四、检测内存信息
Windows 提供了 GlobalMemoryStatusEx() API,可直接获取物理内存总量和可用内存。
示例代码:获取内存信息
#include <iostream>
#include <windows.h>
void GetMemoryInfo() {
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
std::cout << "物理内存总量: "
<< (statex.ullTotalPhys / (1024 * 1024 * 1024))
<< " GB" << std::endl;
std::cout << "可用物理内存: "
<< (statex.ullAvailPhys / (1024 * 1024 * 1024))
<< " GB" << std::endl;
std::cout << "内存使用率: "
<< statex.dwMemoryLoad << "%" << std::endl;
}
五、整合完整代码
下面给出一个完整的 C++ 程序,能够同时检测 CPU 信息 和 内存信息。
#include <iostream>
#include <windows.h>
#include <intrin.h>
using namespace std;
void GetCPUInfo() {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
cout << "CPU 核心数: " << sysInfo.dwNumberOfProcessors << endl;
int cpuInfo[4] = { -1 };
char cpuBrand[0x40];
__cpuid(cpuInfo, 0x80000002);
memcpy(cpuBrand, cpuInfo, sizeof(cpuInfo));
__cpuid(cpuInfo, 0x80000003);
memcpy(cpuBrand + 16, cpuInfo, sizeof(cpuInfo));
__cpuid(cpuInfo, 0x80000004);
memcpy(cpuBrand + 32, cpuInfo, sizeof(cpuInfo));
cout << "CPU 型号: " << cpuBrand << endl;
}
void GetMemoryInfo() {
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
cout << "物理内存总量: "
<< (statex.ullTotalPhys / (1024 * 1024 * 1024))
<< " GB" << endl;
cout << "可用物理内存: "
<< (statex.ullAvailPhys / (1024 * 1024 * 1024))
<< " GB" << endl;
cout << "内存使用率: "
<< statex.dwMemoryLoad << "%" << endl;
}
int main() {
cout << "===== 系统硬件检测 =====" << endl;
GetCPUInfo();
cout << "------------------------" << endl;
GetMemoryInfo();
cout << "========================" << endl;
return 0;
}
六、运行效果
编译运行后,输出示例:
===== 系统硬件检测 =====
CPU 核心数: 8
CPU 型号: Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
------------------------
物理内存总量: 16 GB
可用物理内存: 10 GB
内存使用率: 37%
========================
七、总结
通过本文,你学会了如何:
相关教程
2024-09-01
2024-03-14
2024-03-19
2024-11-18
2024-07-30
2024-08-29
2024-11-03
2024-03-09
2024-06-21
2024-09-23
2025-08-16
2025-08-14
2025-08-14
2025-08-14
2025-08-13
2025-08-13
copyright © 2012-2025 系统家园网 m.hnzkhbsb.com 版权声明