gpt4 book ai didi

c++ - 处理器数量与 CPUZ 不匹配

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:00:32 25 4
gpt4 key购买 nike

我想知道 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com