2022年6月10日 星期五

Windows API的GetLogicalProcessorInformation可取得當前電腦的物理核心數邏輯核心數

 https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation

 http://msdn.microsoft.com/en-us/library/ms683194(v=vs.85).aspx
GetLogicalProcessorInformation function

  GetLogicalProcessorInformation
http://msdn.microsoft.com/en-us/library/ms686694(v=vs.85).aspx
SYSTEM_LOGICAL_PROCESSOR_INFORMATION structure

http://msdn.microsoft.com/en-us/library/ms684197(v=vs.85).aspx
LOGICAL_PROCESSOR_RELATIONSHIP enumeration

http://msdn.microsoft.com/en-us/library/ms681979(v=vs.85).aspx
CACHE_DESCRIPTOR structure

http://msdn.microsoft.com/en-us/library/ms684844(v=vs.85).aspx
PROCESSOR_CACHE_TYPE enumeration

GetProcessorCoreCount(DWORD &PhysicalProcessorCoreCount,DWORD &LogicalProcessorCoreCount )
{
    typedef BOOL(WINAPI *LPFN_GLPI)(
        PSYSTEM_LOGICAL_PROCESSOR_INFORMATION,
        PDWORD);

    LPFN_GLPI glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");

    if (NULL == glpi)
        return 0;

    PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
    DWORD returnLength = 0;
     PhysicalProcessorCoreCount = 0;
     LogicalProcessorCoreCount = 0;
    while (true)
    {
        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)
                    return 0;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            break;
        }
    }

    PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = buffer;

    DWORD byteOffset = 0;
    while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength)
    {
        switch (ptr->Relationship)
        {
        case RelationProcessorCore:
        {
            ++PhysicalProcessorCoreCount;

            // count the logical processor, which is equal the count of digital 1's of ptr->ProcessorMask
            ULONG_PTR   ProcessorMask = ptr->ProcessorMask;
            while (ProcessorMask != 0)
            {
                ProcessorMask &= ProcessorMask - 1;
                LogicalProcessorCoreCount++;
            }
            break;
        }
        default:
            break;
        }
        byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
        ++ptr;
    }
    free(buffer);
    return -1;
}

 

https://en.wikipedia.org/wiki/Hyper-threading

 使用GetLogicalProcessorInformation获取逻辑处理器的详细信息(NUMA节点数、物理CPU数、CPU核心数、逻辑CPU数、各级Cache)

https://www.cnblogs.com/findumars/p/4805207.html 


https://stackoverflow.com/questions/66130195/delphi-getlogicalprocessorinformation-x64