Skip to content

Instantly share code, notes, and snippets.

@ganesh-k13
Created January 26, 2020 06:19
Show Gist options
  • Save ganesh-k13/e692e53699a6ca31d50ca7b4fbb5f2e4 to your computer and use it in GitHub Desktop.
Save ganesh-k13/e692e53699a6ca31d50ca7b4fbb5f2e4 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <iostream>
#include <thread>
int getNumberOfCPUs(void)
{
unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
// std::cout << "Thread: " << concurentThreadsSupported << std::endl;
#if defined _WIN32
SYSTEM_INFO sysinfo;
#if (defined(_M_ARM) || defined(_M_ARM64) || defined(_M_X64) || defined(WINRT)) && _WIN32_WINNT >= 0x501
GetNativeSystemInfo( &sysinfo );
#else
GetSystemInfo( &sysinfo );
#endif
return (int)sysinfo.dwNumberOfProcessors;
#elif defined __ANDROID__
static int ncpus = getNumberOfCPUsImpl();
return ncpus;
#elif defined __linux__ || defined __GLIBC__ || defined __HAIKU__ || defined __EMSCRIPTEN__
// return (int)sysconf( _SC_NPROCESSORS_ONLN );
cpu_set_t cpu_set;
sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
// std::cout << "CPU: " << CPU_COUNT(&cpu_set) << std::endl;
return CPU_COUNT(&cpu_set);
#elif defined __APPLE__
int numCPU=0;
int mib[4];
size_t len = sizeof(numCPU);
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, 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;
}
return (int)numCPU;
#else
return 1;
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment