7

Using unmanaged C++ on a Windows platform, is there a simple way to detect the number of processor cores my host machine has?

Paul Mitchell
  • 3,241
  • 1
  • 19
  • 22
  • 5
    Related question: http://stackoverflow.com/questions/150355 – macbirdie May 18 '09 at 14:10
  • possible duplicate of [Programmatically find the number of cores on a machine](http://stackoverflow.com/questions/150355/programmatically-find-the-number-of-cores-on-a-machine) – sschuberth Feb 25 '15 at 13:13

4 Answers4

12

You can use GetLogicalProcessorInformation to get the info you need.

ETA:

As mentioned in the question a commenter linked to, another (easier) way to do it would be via GetSystemInfo:

SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );

numCPU = sysinfo.dwNumberOfProcessors;

Seems like GetLogicalProcessorInformation would give you more detailed info, but if all you need is the number of processors, GetSystemInfo would probably work just fine.

Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177
2

I've noticed there's an environment variable NUMBER_OF_PROCESSORS on XP, but I couldn't find it on Microsoft's site. I believe this would be the easiest way, though.

Bastien Léonard
  • 60,478
  • 20
  • 78
  • 95
0
size_t getProcessorCores()
{
    DWORD process, system;
    if(GetProcessAffinityMask(GetCurrentProcess(), &process, &system))
    {
        int count = 0;
        for(int i = 0; i < 32; i++)
            if(system & (1 << i))
                count++;
        return count;
    }
    // may be we hav't PROCESS_QUERY_INFORMATION access right
    SYSTEM_INFO sysinfo;
    GetSystemInfo( &sysinfo );
    return sysinfo.dwNumberOfProcessors;
}

size_t getAvailableProcessorCores()
{
    DWORD process, system;
    if(GetProcessAffinityMask(GetCurrentProcess(), &process, &system))
    {
        int count = 0;
        for(int i = 0; i < 32; i++)
            if(process & (1 << i))
                count++;
        return count;
    }
    // may be we hav't PROCESS_QUERY_INFORMATION access right
    SYSTEM_INFO sysinfo;
    GetSystemInfo( &sysinfo );
    return sysinfo.dwNumberOfProcessors;
}
0

Check out GetLogicalProcessorInformation

devdimi
  • 2,432
  • 19
  • 18