aboutsummaryrefslogtreecommitdiff
path: root/src/common/cpucores.h
blob: 370c3cec1cb3d8cc5530d97dab578d8b9d23f59e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
///////////////////////////////////////////////////////////////////////////////
//
/// \file       cpucores.h
/// \brief      Get the number of online CPU cores
//
//  Author:     Lasse Collin
//
//  This file has been put into the public domain.
//  You can do whatever you want with this file.
//
///////////////////////////////////////////////////////////////////////////////

#ifndef CPUCORES_H
#define CPUCORES_H

#if defined(HAVE_CPUCORES_SYSCONF)
#	include <unistd.h>

#elif defined(HAVE_CPUCORES_SYSCTL)
#	ifdef HAVE_SYS_PARAM_H
#		include <sys/param.h>
#	endif
#	ifdef HAVE_SYS_SYSCTL_H
#		include <sys/sysctl.h>
#	endif
#endif


static inline uint32_t
cpucores(void)
{
	uint32_t ret = 0;

#if defined(HAVE_CPUCORES_SYSCONF)
	const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
	if (cpus > 0)
		ret = (uint32_t)(cpus);

#elif defined(HAVE_CPUCORES_SYSCTL)
	int name[2] = { CTL_HW, HW_NCPU };
	int cpus;
	size_t cpus_size = sizeof(cpus);
	if (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -1
			&& cpus_size == sizeof(cpus) && cpus > 0)
		ret = (uint32_t)(cpus);
#endif

	return ret;
}

#endif