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