Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of cores in Win32?

I'm writing a program in C on windows that needs to run as many threads as available cores. But I dont know how to get the number of cores. Any ideas?

like image 548
Alan Avatar asked Apr 11 '10 23:04

Alan


3 Answers

Type "cmd" on windows startup and open "cmd.exe". Now type in the following command:

WMIC CPU Get /Format:List

You will find the entries like - "NumberOfCores" and "NumberOfLogicalProcessors". Typically the logical-processors are achieved by threading. Therefore the relation would typically go like;

NumberOfLogicalProcessors = NumberOfCores * Number-of-Threads-per-Core.

Since each core serves a processing-unit, therefore with threading, logical-processing-unit is realized in real space.

More info here.

like image 182
parasrish Avatar answered Oct 14 '22 15:10

parasrish


You can call the GetSystemInfo WinAPI function; it returns a SYSTEM_INFO struct, which has the number of processors (which is the number of cores on a system with multiple core CPUs).

like image 29
James McNellis Avatar answered Oct 14 '22 15:10

James McNellis


As @Changming-Sun mentioned in a comment above, GetSysInfo returns the number of logical processors, which is not always the same as the number of processor cores. On machines that support hyperthreading (including most modern Intel CPUs) more than one thread can run on the same core (technically, more than one thread will have its thread context loaded on the same core). Getting the number of processor cores requires a call to GetLogicalProcessorInformation and a little bit of coding work. Basically, you get back a list of SYSTEM_LOGICAL_PROCESSOR_INFORMATION entries, and you have to count the number of entries with RelationProcessorCore set. A good example of how to code this in the GetLogicalProcessorInformation documentation provided by Microsoft: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation

like image 20
DSimkin Avatar answered Oct 14 '22 14:10

DSimkin