NetInverse Developers Blog

March 8, 2009
Category: Windows API — Tags: , , — admin @ 8:24 pm

GetLogicalProcessorInformation: Retrieves information about logical processors and related hardware.

You can use this new API easily to detect how many CPUs or Cores on your machine. Otherwise, you may have to deal with CPUID with the Intel and AMD extensions. You can also use this API to find out which virtual processors are associated with the same physical processor.

Example from MSDN

    #include <windows.h>
    #include <malloc.h>
    #include <stdio.h>
    #include <tchar.h>

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

    int _cdecl _tmain ()
    {
        BOOL done;
        BOOL rc;
        DWORD returnLength;
        DWORD procCoreCount;
        DWORD byteOffset;
        PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, ptr;
        LPFN_GLPI Glpi;

        Glpi = (LPFN_GLPI) GetProcAddress(
                                GetModuleHandle(TEXT("kernel32")),
                                "GetLogicalProcessorInformation");
        if (NULL == Glpi)
        {
            _tprintf(
              TEXT("GetLogicalProcessorInformation is not supported.\n"));
            return (1);
        }

        done = FALSE;
        buffer = NULL;
        returnLength = 0;

        while (!done)
        {
            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)
                    {
                        _tprintf(TEXT("Allocation failure\n"));
                        return (2);
                    }
                }
                else
                {
                    _tprintf(TEXT("Error %d\n"), GetLastError());
                    return (3);
                }
            }
            else done = TRUE;
        }

        procCoreCount = 0;
        byteOffset = 0;

        ptr=buffer;
        while (byteOffset < returnLength)
        {
            switch (ptr->Relationship)
            {
                case RelationProcessorCore:
                    procCoreCount++;
                    break;

                default:
                    break;
            }
            byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
            ptr++;
        }

        _tprintf(TEXT("Number of active processor cores: %d\n"),
                 procCoreCount);
        free (buffer);

        return 0;
    }

©2009 NetInverse. All rights reserved. Powered by WordPress