1 ///////////////////////////////////////////////////////////////////////////////
3 /// \file tuklib_cpucores.c
4 /// \brief Get the number of CPU cores online
6 // Author: Lasse Collin
8 // This file has been put into the public domain.
9 // You can do whatever you want with this file.
11 ///////////////////////////////////////////////////////////////////////////////
13 #include "tuklib_cpucores.h"
15 #if defined(_WIN32) || defined(__CYGWIN__)
17 # define _WIN32_WINNT 0x0500
22 #elif defined(TUKLIB_CPUCORES_SCHED_GETAFFINITY)
26 #elif defined(TUKLIB_CPUCORES_CPUSET)
27 # include <sys/param.h>
28 # include <sys/cpuset.h>
30 #elif defined(TUKLIB_CPUCORES_SYSCTL)
31 # ifdef HAVE_SYS_PARAM_H
32 # include <sys/param.h>
34 # include <sys/sysctl.h>
36 #elif defined(TUKLIB_CPUCORES_SYSCONF)
40 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
41 # include <sys/param.h>
42 # include <sys/pstat.h>
51 #if defined(_WIN32) || defined(__CYGWIN__)
53 GetSystemInfo(&sysinfo
);
54 ret
= sysinfo
.dwNumberOfProcessors
;
56 #elif defined(TUKLIB_CPUCORES_SCHED_GETAFFINITY)
58 if (sched_getaffinity(0, sizeof(cpu_mask
), &cpu_mask
) == 0)
59 ret
= CPU_COUNT(&cpu_mask
);
61 #elif defined(TUKLIB_CPUCORES_CPUSET)
63 if (cpuset_getaffinity(CPU_LEVEL_WHICH
, CPU_WHICH_PID
, -1,
64 sizeof(set
), &set
) == 0) {
66 ret
= CPU_COUNT(&set
);
68 for (unsigned i
= 0; i
< CPU_SETSIZE
; ++i
)
69 if (CPU_ISSET(i
, &set
))
74 #elif defined(TUKLIB_CPUCORES_SYSCTL)
75 int name
[2] = { CTL_HW
, HW_NCPU
};
77 size_t cpus_size
= sizeof(cpus
);
78 if (sysctl(name
, 2, &cpus
, &cpus_size
, NULL
, 0) != -1
79 && cpus_size
== sizeof(cpus
) && cpus
> 0)
82 #elif defined(TUKLIB_CPUCORES_SYSCONF)
83 # ifdef _SC_NPROCESSORS_ONLN
85 const long cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
88 const long cpus
= sysconf(_SC_NPROC_ONLN
);
93 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
94 struct pst_dynamic pst
;
95 if (pstat_getdynamic(&pst
, sizeof(pst
), 1, 0) != -1)
96 ret
= pst
.psd_proc_cnt
;