作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想知道 cpu 核心的数量,所以我有这段代码
SYSTEM_INFO siSysInfo;
DWORD getProcessorNum()
{
GetSystemInfo(&siSysInfo);
return siSysInfo.dwNumberOfProcessors;
}
它返回 4。但是当我用 CPUZ 检查我的结果时,它返回 2Cores 4Thraeds
os 我用这段代码尝试 __cpuid
unsigned regs[4];
__cpuid(regs,4);
cores = ((regs[0] >> 26) & 0x3f) + 1;cout << " cpu cores: " << cores << endl;
它返回 8 个核心。
你能告诉我,我的代码错了吗?
我在配备 i3 处理器的 Win7x64 平台上使用 MSVC++2010 运行这段代码。
最佳答案
检查 CPU 的数量一点也不简单(主要是由于多核/插槽/CPU 设计)。 GetSystemInfo
调用返回系统看到的执行线程数量,CPUID 根据 CPU 拓扑有不同的值(请参阅英特尔开发人员手册)。
我构建了一些东西来捕捉所有情况,你可能会发现它很有用:
static void GetProcessorTopology(size_t& nPhysical, size_t& nCores, size_t& nSystemThreads, size_t& nHWThreads, size_t& nThreadsPerCore)
{
int nInfo[4];
SYSTEM_INFO pSystemInfo;
IsWOW64() ? GetNativeSystemInfo(&pSystemInfo) : GetSystemInfo(&pSystemInfo);
nSystemThreads = pSystemInfo.dwNumberOfProcessors;
if(TestTopologyLevel(nInfo,0x0,1) || TestTopologyLevel(nInfo,0x1,1))
{
nThreadsPerCore = nInfo[1] & 0xFFFF;
if(TestTopologyLevel(nInfo,0x0,2) || TestTopologyLevel(nInfo,0x1,2))
{
nHWThreads = nInfo[1] & 0xFFFF;
nCores = (nThreadsPerCore == 0) ? GetCoreCount(nInfo) : nHWThreads / nThreadsPerCore;
}
else
{
nHWThreads = nSystemThreads;
nCores = GetCoreCount(nInfo);
}
}
else
{
nThreadsPerCore = 1;
nHWThreads = nSystemThreads;
nCores = GetCoreCount(nInfo);
}
nPhysical = (nCores == 0) ? 1 : (nSystemThreads / nThreadsPerCore) / nCores;
}
static inline bool TestTopologyLevel(int* pInfo, int nMode, int nLevel)
{
__cpuidex(pInfo,0xB,nMode);
return ((pInfo[2] >> 8) & 0xFF) == nLevel;
}
static inline size_t GetCoreCount(int* nInfo)
{
__cpuid(nInfo,0);
if(nInfo[0] >= 4)
{
__cpuidex(nInfo,0x4,0x0);
return (nInfo[0] >> 26) + 1;
}
else
{
__cpuid(nInfo,0x80000000);
int nCPUID = nInfo[0];
__cpuid(nInfo,1);
if(nInfo[3] & 0x10000000 && nCPUID >= 0x80000008)
{
__cpuid(nInfo,0x80000008);
return (nInfo[2] & 0xFF) + 1;
}
}
return 1;
}
关于c++ - 处理器数量与 CPUZ 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8267659/
我想知道 cpu 核心的数量,所以我有这段代码 SYSTEM_INFO siSysInfo; DWORD getProcessorNum() { GetSystemInfo(&siSysInf
我是一名优秀的程序员,十分优秀!