日期:2014-05-16  浏览次数:21391 次

Windows下获取逻辑cpu数量和cpu核数量

代码可在Windows NT下正常运行

具体API说明请参照如下文档:

GetLogicalProcessorInformation

点击打开链接

点击打开链接

点击打开链接


typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);

DWORD CountSetBits(ULONG_PTR bitMask)
{
    DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1;
    DWORD bitSetCount = 0;
    ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT;    
    DWORD i;
    
    for (i = 0; i <= LSHIFT; ++i)
    {
        bitSetCount += ((bitMask & bitTest)?1:0);
        bitTest/=2;
    }

    return bitSetCount;
}
LPFN_GLPI glpi;
glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")),"GetLogicalProcessorInformation");
if (NULL == glpi) 
{
	printf("GetLogicalProcessorInformation is not supported.\n");
}
BOOL done = FALSE;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
DWORD returnLength = 0;
while (!done)
{
	DWORD rc = glpi(buffer, &returnLength);

	if (FALSE == rc) 
	{
		if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) 
		{
			if (buffer) 
				free(buffer);

			buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);

			if (NULL == buffer) 
			{
				printf("Error: Allocation failure\n");
				return (2);
			}
		} 
		else 
		{
			printf("Error %d\n", GetLastError());
			return (3);
		}
	} 
	else
	{
		done = TRUE;
	}
}

ptr = buffer;
DWORD byteOffset = 0;
DWORD logicalProcessorCount = 0;
DWORD processorCoreCount = 0;

while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) 
{
	switch (ptr->Relationship) 
	{
		case RelationProcessorCore:
			processorCoreCount++;
			logicalProcessorCount += CountSetBits(ptr->ProcessorMask);
			break;
	}
	byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
	ptr++;
}
printf("logical:%d  core:%d\n", logicalProcessorCount, processorCoreCount);