Can I know the number of computer cores through the program?

Asked 2 years ago, Updated 2 years ago, 35 views

Regardless of the platform, Is there a way to find out how many cores it is using C/C++

If you don't have that method, Please use it according to the platform.

c++ c core

2022-09-22 22:35

1 Answers

For C++11 or higher, see std::thread::hardware_concurrent

//return 0 if detect fails.
unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );

numCPU = sysinfo.dwNumberOfProcessors;
numCPU = sysconf( _SC_NPROCESSORS_ONLN );
int mib[4];
size_t len = sizeof(numCPU); 

/* /* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // If this doesn't work, try HW_NCPU;

/* /* get the number of CPUs from the system */
sysctl(mib, 2, &numCPU, &len, NULL, 0);

if( numCPU < 1 ) 
{
     mib[1] = HW_NCPU;
     sysctl( mib, 2, &numCPU, &len, NULL, 0 );

     if( numCPU < 1 )
     {
          numCPU = 1;
     }
}
numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
numCPU = sysconf( _SC_NPROC_ONLN );
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.