10bb303c1c94e64dbb1f9c1f523f702fb33fb5f5
[m6w6/libmemcached] / libtest / cpu.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * libtest
4 *
5 * Copyright (C) 2012 Data Differential, http://datadifferential.com/
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 3 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <config.h>
23 #include <libtest/common.h>
24
25 #include <unistd.h>
26
27 #if defined(HAVE_SYS_SYSCTL_H) && HAVE_SYS_SYSCTL_H
28 #include <sys/sysctl.h>
29 #endif
30
31 namespace libtest {
32
33 size_t number_of_cpus()
34 {
35 size_t number_of_cpu= 1;
36 #if TARGET_OS_LINUX
37 number_of_cpu= sysconf(_SC_NPROCESSORS_ONLN);
38 #elif defined(HAVE_SYS_SYSCTL_H) && defined(CTL_HW) && defined(HW_NCPU) && defined(HW_AVAILCPU) && defined(HW_NCPU)
39 int mib[4];
40 size_t len= sizeof(number_of_cpu);
41
42 /* set the mib for hw.ncpu */
43 mib[0] = CTL_HW;
44 mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
45
46 /* get the number of CPUs from the system */
47 sysctl(mib, 2, &number_of_cpu, &len, NULL, 0);
48
49 if (number_of_cpu < 1)
50 {
51 mib[1]= HW_NCPU;
52 sysctl(mib, 2, &number_of_cpu, &len, NULL, 0 );
53
54 if (number_of_cpu < 1 )
55 {
56 number_of_cpu = 1;
57 }
58 }
59 #else
60 fprintf(stderr, "Going with guessing\n");
61 #endif
62
63 return number_of_cpu;
64 }
65
66 } // namespace libtest