]> icculus.org git repositories - icculus/xz.git/blob - src/common/cpucores.h
Cleanups to the code that detects the amount of RAM and
[icculus/xz.git] / src / common / cpucores.h
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       cpucores.h
4 /// \brief      Get the number of online CPU cores
5 //
6 //  This code has been put into the public domain.
7 //
8 //  This library is distributed in the hope that it will be useful,
9 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 //
12 ///////////////////////////////////////////////////////////////////////////////
13
14 #ifndef CPUCORES_H
15 #define CPUCORES_H
16
17 #if defined(HAVE_NCPU_SYSCONF)
18 #       include <unistd.h>
19
20 #elif defined(HAVE_NCPU_SYSCTL)
21 #       ifdef HAVE_SYS_PARAM_H
22 #               include <sys/param.h>
23 #       endif
24 #       ifdef HAVE_SYS_SYSCTL_H
25 #               include <sys/sysctl.h>
26 #       endif
27 #endif
28
29
30 static inline uint32_t
31 cpucores(void)
32 {
33         uint32_t ret = 0;
34
35 #if defined(HAVE_CPUCORES_SYSCONF)
36         const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
37         if (cpus > 0)
38                 ret = (uint32_t)(cpus);
39
40 #elif defined(HAVE_CPUCORES_SYSCTL)
41         int name[2] = { CTL_HW, HW_NCPU };
42         int cpus;
43         size_t cpus_size = sizeof(cpus);
44         if (!sysctl(name, &cpus, &cpus_size, NULL, NULL)
45                         && cpus_size == sizeof(cpus) && cpus > 0)
46                 ret = (uint32_t)(cpus);
47 #endif
48
49         return ret;
50 }
51
52 #endif