Requirement
During programming, especially in program development involving the system environment, we may need to dynamically obtain the number of available CPU cores in the current machine. For example, when we need to perform parallel computing, we may determine the degree of Parallelism Based on the number of CPU cores. Therefore, we need to obtain the number of available CPU cores in the current machine in the C program.
Method
To meet cross-platform requirements, we also need to consider how to obtain the number of machine processor cores on different platforms. Here we consider Linux and Windows. different platforms have different methods to obtain the number of processor cores.
On Windows, we can use the GetSystemInfo () function to obtain some hardware and software information of the current system. One of them is the number of processors in the current machine. Use the following statement to obtain the required information:
SYSTEM_INFO info;
GetSystemInfo (& info );
Return info. dwNumberOfProcessors;
On the Linux platform, we can use sysconf () or get_nprocs () to obtain the number of processor cores. The following sections describe:
Sysconf () is provided by unistd. h. To use this function, # include <unistd. h> is required. The parameter can be _ SC _NPROCESSORS_CONF or _ SC _NPROCESSORS_ONLN. Sysconf (_ SC _NPROCESSORS_CONF) returns the number of available cores in the system, but the value includes the number of disabled cores in the system. Therefore, this value does not represent the number of available cores in the current system. The return value of sysconf (_ SC _NPROCESSORS_ONLN) actually represents the number of available cores of the system.
The gnu c Library provides another method to obtain the number of available machine cores. Function int
Get_nprocs_conf (void) and int get_nprocs (void) are defined in sys/sysinfo. h. These two functions can be used to obtain the number of machine cores. The returned value of get_nprocs_conf (void) is similar to that of sysconf (_ SC _NPROCESSORS_CONF), but the current number of available cores of the table name is not true. get_nprocs
The return value of (void) is similar to that of sysconf (_ SC _NPROCESSORS_ONLN), which truly reflects the number of available cores.
Cross-platform Functions
The function for cross-platform acquisition of the current number of available cores of the system is as follows:
[Cpp]
Int_t get_CPU_core_num ()
{
# If defined (WIN32)
SYSTEM_INFO info;
GetSystemInfo (& info );
Return info. dwNumberOfProcessors;
# Elif defined (LINUX) | defined (SOLARIS) | defined (AIX)
Return get_nprocs (); // GNU fuction
# Else
# Operating systems not supported by error
# Endif
}