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
= (uint32_t)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
= (uint32_t)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 // On OpenBSD HW_NCPUONLINE tells the number of processor cores that
76 // are online so it is preferred over HW_NCPU which also counts cores
77 // that aren't currently available. The number of cores online is
78 // often less than HW_NCPU because OpenBSD disables simultaneous
79 // multi-threading (SMT) by default.
81 int name
[2] = { CTL_HW
, HW_NCPUONLINE
};
83 int name
[2] = { CTL_HW
, HW_NCPU
};
86 size_t cpus_size
= sizeof(cpus
);
87 if (sysctl(name
, 2, &cpus
, &cpus_size
, NULL
, 0) != -1
88 && cpus_size
== sizeof(cpus
) && cpus
> 0)
91 #elif defined(TUKLIB_CPUCORES_SYSCONF)
92 # ifdef _SC_NPROCESSORS_ONLN
94 const long cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
97 const long cpus
= sysconf(_SC_NPROC_ONLN
);
100 ret
= (uint32_t)cpus
;
102 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
103 struct pst_dynamic pst
;
104 if (pstat_getdynamic(&pst
, sizeof(pst
), 1, 0) != -1)
105 ret
= (uint32_t)pst
.psd_proc_cnt
;