xref: /freebsd/contrib/xz/src/common/tuklib_cpucores.c (revision ec0e626bafb335b30c499d06066997f54b10c092)
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       tuklib_cpucores.c
4 /// \brief      Get the number of CPU cores online
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 #include "tuklib_cpucores.h"
14 
15 #if defined(_WIN32) || defined(__CYGWIN__)
16 #	ifndef _WIN32_WINNT
17 #		define _WIN32_WINNT 0x0500
18 #	endif
19 #	include <windows.h>
20 
21 #elif defined(TUKLIB_CPUCORES_SYSCTL)
22 #	ifdef HAVE_SYS_PARAM_H
23 #		include <sys/param.h>
24 #	endif
25 #	include <sys/sysctl.h>
26 
27 #elif defined(TUKLIB_CPUCORES_SYSCONF)
28 #	include <unistd.h>
29 
30 // HP-UX
31 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
32 #	include <sys/param.h>
33 #	include <sys/pstat.h>
34 #endif
35 
36 
37 extern uint32_t
38 tuklib_cpucores(void)
39 {
40 	uint32_t ret = 0;
41 
42 #if defined(_WIN32) || defined(__CYGWIN__)
43 	SYSTEM_INFO sysinfo;
44 	GetSystemInfo(&sysinfo);
45 	ret = sysinfo.dwNumberOfProcessors;
46 
47 #elif defined(TUKLIB_CPUCORES_SYSCTL)
48 	int name[2] = { CTL_HW, HW_NCPU };
49 	int cpus;
50 	size_t cpus_size = sizeof(cpus);
51 	if (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -1
52 			&& cpus_size == sizeof(cpus) && cpus > 0)
53 		ret = cpus;
54 
55 #elif defined(TUKLIB_CPUCORES_SYSCONF)
56 #	ifdef _SC_NPROCESSORS_ONLN
57 	// Most systems
58 	const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
59 #	else
60 	// IRIX
61 	const long cpus = sysconf(_SC_NPROC_ONLN);
62 #	endif
63 	if (cpus > 0)
64 		ret = cpus;
65 
66 #elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)
67 	struct pst_dynamic pst;
68 	if (pstat_getdynamic(&pst, sizeof(pst), 1, 0) != -1)
69 		ret = pst.psd_proc_cnt;
70 #endif
71 
72 	return ret;
73 }
74