tuklib_cpucores.c revision 207753
1/////////////////////////////////////////////////////////////////////////////// 2// 3/// \file tuklib_cpucores.c 4/// \brief Get the number of CPU cores online 5// 6// Author: Lasse Collin 7// 8// This file has been put into the public domain. 9// You can do whatever you want with this file. 10// 11/////////////////////////////////////////////////////////////////////////////// 12 13#include "tuklib_cpucores.h" 14 15#if defined(TUKLIB_CPUCORES_SYSCTL) 16# ifdef HAVE_SYS_PARAM_H 17# include <sys/param.h> 18# endif 19# include <sys/sysctl.h> 20 21#elif defined(TUKLIB_CPUCORES_SYSCONF) 22# include <unistd.h> 23#endif 24 25 26extern uint32_t 27tuklib_cpucores(void) 28{ 29 uint32_t ret = 0; 30 31#if defined(TUKLIB_CPUCORES_SYSCTL) 32 int name[2] = { CTL_HW, HW_NCPU }; 33 int cpus; 34 size_t cpus_size = sizeof(cpus); 35 if (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -1 36 && cpus_size == sizeof(cpus) && cpus > 0) 37 ret = (uint32_t)cpus; 38 39#elif defined(TUKLIB_CPUCORES_SYSCONF) 40# ifdef _SC_NPROCESSORS_ONLN 41 // Most systems 42 const long cpus = sysconf(_SC_NPROCESSORS_ONLN); 43# else 44 // IRIX 45 const long cpus = sysconf(_SC_NPROC_ONLN); 46# endif 47 if (cpus > 0) 48 ret = (uint32_t)cpus; 49#endif 50 51 return ret; 52} 53