GetLogicalProcessorInformation

最近在看《windows核心编程》,看到如何获得处理器信息,不是太明白,下面是获得处理器核心数的代码,我自己加了一些注释。

//获得处理器核心数
 void ShowProcessors()
 {
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pBuffer = NULL;
DWORD dwSize = 0;
DWORD procCoreCount;

//获得有dwSize的大小
BOOL bResult = GetLogicalProcessorInformation(pBuffer, &dwSize);
if(GetLastError() != ERROR_INSUFFICIENT_BUFFER){
    _tprintf(TEXT("Impossible to get processor information\n"));
    return;
}

//获得SYSTEM_LOGICAL_PROCESSOR_INFORMATION数组,数组中包含了所有逻辑处理器信息
pBuffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(dwSize);
bResult = GetLogicalProcessorInformation(pBuffer, &dwSize);
if(!bResult){
    free(pBuffer);
    _tprintf(TEXT("Impossible to get processor information\n"));
    return;
}

procCoreCount = 0;
//逻辑处理器数量
DWORD lpiCount = dwSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
for(DWORD current = 0; current < lpiCount; current++){
    //逻辑处理器的Relationship为RelationProcessorCore,表示该逻辑处理器是处理器核心
    if(pBuffer[current].Relationship == RelationProcessorCore){
        //该标志表示处理器的用途
        if(pBuffer[current].ProcessorCore.Flags == 1){
            _tprintf(TEXT(" + one CPU core (HyperThreading)\n"));
        } else {
            _tprintf(TEXT("+ one CPU socket\n"));
        }
        procCoreCount++;

    }
}
_tprintf(TEXT("-> %d active CPU(s) \n"), procCoreCount);

free(pBuffer);
 }

一开始不懂为什么要调用两次GetLogicalProcessorInformation函数,后来查了一下msdn,得知第一次是获得系统有多少个逻辑处理器数,也就是需要传递多大的SYSTEM_LOGICAL_PROCESSOR_INFORMATION数组给GetLogicalProcessorInformation函数,第二次调用的时候,函数会给pBuffer数组赋值。下面是MSDN上给出的关于函数的注解:

函数原型:
BOOL WINAPI GetLogicalProcessorInformation(
Out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer,
Inout PDWORD ReturnLength
);

Buffer [out]
A pointer to a buffer that receives an array of SYSTEM_LOGICAL_PROCESSOR_INFORMATION structures. If the function fails, the contents of this buffer are undefined.

ReturnLength [in, out]
On input, specifies the length of the buffer pointed to by Buffer, in bytes. If the buffer is large enough to contain all of the data, this function succeeds and ReturnLength is set to the number of bytes returned. If the buffer is not large enough to contain all of the data, the function fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and ReturnLength is set to the buffer length required to contain all of the data. If the function fails with an error other than ERROR_INSUFFICIENT_BUFFER, the value of ReturnLength is undefined.

参考:
http://blog.csdn.net/zyl910/article/details/7547264

你可能感兴趣的:(GetLogicalProcessorInformation)