1 /* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */ 2 // vim: expandtab:ts=8:sw=4:softtabstop=4: 3 /////////////////////////////////////////////////////////////////////////////// 4 // 5 /// \file cpucores.h 6 /// \brief Get the number of online CPU cores 7 // 8 // Author: Lasse Collin 9 // 10 // This file has been put into the public domain. 11 // You can do whatever you want with this file. 12 // 13 /////////////////////////////////////////////////////////////////////////////// 14 15 #ifndef CPUCORES_H 16 #define CPUCORES_H 17 18 #if defined(HAVE_CPUCORES_SYSCONF) 19 # include <unistd.h> 20 21 #elif defined(HAVE_CPUCORES_SYSCTL) 22 # ifdef HAVE_SYS_PARAM_H 23 # include <sys/param.h> 24 # endif 25 # ifdef HAVE_SYS_SYSCTL_H 26 # include <sys/sysctl.h> 27 # endif 28 #endif 29 30 31 static inline uint32_t cpucores(void)32cpucores(void) 33 { 34 uint32_t ret = 0; 35 36 #if defined(HAVE_CPUCORES_SYSCONF) 37 const long cpus = sysconf(_SC_NPROCESSORS_ONLN); 38 if (cpus > 0) 39 ret = (uint32_t)(cpus); 40 41 #elif defined(HAVE_CPUCORES_SYSCTL) 42 int name[2] = { CTL_HW, HW_NCPU }; 43 int cpus; 44 size_t cpus_size = sizeof(cpus); 45 if (!sysctl(name, &cpus, &cpus_size, NULL, NULL) 46 && cpus_size == sizeof(cpus) && cpus > 0) 47 ret = (uint32_t)(cpus); 48 #endif 49 50 return ret; 51 } 52 53 #endif 54