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_CPUSET)
23 # include <sys/param.h>
24 # include <sys/cpuset.h>
26 #elif defined(TUKLIB_CPUCORES_SYSCTL)
27 # ifdef HAVE_SYS_PARAM_H
28 # include <sys/param.h>
30 # include <sys/sysctl.h>
32 #elif defined(TUKLIB_CPUCORES_SYSCONF)
36 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
37 # include <sys/param.h>
38 # include <sys/pstat.h>
47 #if defined(_WIN32) || defined(__CYGWIN__)
49 GetSystemInfo(&sysinfo
);
50 ret
= sysinfo
.dwNumberOfProcessors
;
52 #elif defined(TUKLIB_CPUCORES_CPUSET)
54 if (cpuset_getaffinity(CPU_LEVEL_WHICH
, CPU_WHICH_PID
, -1,
55 sizeof(set
), &set
) == 0) {
57 ret
= CPU_COUNT(&set
);
59 for (unsigned i
= 0; i
< CPU_SETSIZE
; ++i
)
60 if (CPU_ISSET(i
, &set
))
65 #elif defined(TUKLIB_CPUCORES_SYSCTL)
66 int name
[2] = { CTL_HW
, HW_NCPU
};
68 size_t cpus_size
= sizeof(cpus
);
69 if (sysctl(name
, 2, &cpus
, &cpus_size
, NULL
, 0) != -1
70 && cpus_size
== sizeof(cpus
) && cpus
> 0)
73 #elif defined(TUKLIB_CPUCORES_SYSCONF)
74 # ifdef _SC_NPROCESSORS_ONLN
76 const long cpus
= sysconf(_SC_NPROCESSORS_ONLN
);
79 const long cpus
= sysconf(_SC_NPROC_ONLN
);
84 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
85 struct pst_dynamic pst
;
86 if (pstat_getdynamic(&pst
, sizeof(pst
), 1, 0) != -1)
87 ret
= pst
.psd_proc_cnt
;