tuklib_cpucores.c revision 207842
11573Srgrimes///////////////////////////////////////////////////////////////////////////////
21573Srgrimes//
31573Srgrimes/// \file       tuklib_cpucores.c
41573Srgrimes/// \brief      Get the number of CPU cores online
51573Srgrimes//
61573Srgrimes//  Author:     Lasse Collin
71573Srgrimes//
81573Srgrimes//  This file has been put into the public domain.
91573Srgrimes//  You can do whatever you want with this file.
101573Srgrimes//
111573Srgrimes///////////////////////////////////////////////////////////////////////////////
121573Srgrimes
131573Srgrimes#include "tuklib_cpucores.h"
141573Srgrimes
151573Srgrimes#if defined(TUKLIB_CPUCORES_SYSCTL)
161573Srgrimes#	ifdef HAVE_SYS_PARAM_H
171573Srgrimes#		include <sys/param.h>
181573Srgrimes#	endif
191573Srgrimes#	include <sys/sysctl.h>
201573Srgrimes
211573Srgrimes#elif defined(TUKLIB_CPUCORES_SYSCONF)
221573Srgrimes#	include <unistd.h>
231573Srgrimes#endif
241573Srgrimes
251573Srgrimes
261573Srgrimesextern uint32_t
271573Srgrimestuklib_cpucores(void)
2816454Swollman{
2950476Speter	uint32_t ret = 0;
301573Srgrimes
3116454Swollman#if defined(TUKLIB_CPUCORES_SYSCTL)
321573Srgrimes	int name[2] = { CTL_HW, HW_NCPU };
3379531Sru	int cpus;
341573Srgrimes	size_t cpus_size = sizeof(cpus);
351573Srgrimes	if (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -1
361573Srgrimes			&& cpus_size == sizeof(cpus) && cpus > 0)
371573Srgrimes		ret = (uint32_t)cpus;
381573Srgrimes
391573Srgrimes#elif defined(TUKLIB_CPUCORES_SYSCONF)
401573Srgrimes#	ifdef _SC_NPROCESSORS_ONLN
4159460Sphantom	// Most systems
4259460Sphantom	const long cpus = sysconf(_SC_NPROCESSORS_ONLN);
431573Srgrimes#	else
4484306Sru	// IRIX
451573Srgrimes	const long cpus = sysconf(_SC_NPROC_ONLN);
4679754Sdd#	endif
471573Srgrimes	if (cpus > 0)
489459Sjoerg		ret = (uint32_t)cpus;
491573Srgrimes#endif
509459Sjoerg
511573Srgrimes	return ret;
521573Srgrimes}
531573Srgrimes