Path: blob/master/Utilities/cmliblzma/common/tuklib_cpucores.c
3153 views
// SPDX-License-Identifier: 0BSD12///////////////////////////////////////////////////////////////////////////////3//4/// \file tuklib_cpucores.c5/// \brief Get the number of CPU cores online6//7// Author: Lasse Collin8//9///////////////////////////////////////////////////////////////////////////////1011#include "tuklib_cpucores.h"1213#if defined(_WIN32) || defined(__CYGWIN__)14# ifndef _WIN32_WINNT15# define _WIN32_WINNT 0x050016# endif17# include <windows.h>1819// glibc >= 2.920#elif defined(TUKLIB_CPUCORES_SCHED_GETAFFINITY)21# include <sched.h>2223// FreeBSD24#elif defined(TUKLIB_CPUCORES_CPUSET)25# include <sys/param.h>26# include <sys/cpuset.h>2728#elif defined(TUKLIB_CPUCORES_SYSCTL)29# ifdef HAVE_SYS_PARAM_H30# include <sys/param.h>31# endif32# include <sys/sysctl.h>3334#elif defined(TUKLIB_CPUCORES_SYSCONF)35# include <unistd.h>3637// HP-UX38#elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)39# include <sys/param.h>40# include <sys/pstat.h>41#endif424344extern uint32_t45tuklib_cpucores(void)46{47uint32_t ret = 0;4849#if defined(_WIN32) || defined(__CYGWIN__)50SYSTEM_INFO sysinfo;51GetSystemInfo(&sysinfo);52ret = sysinfo.dwNumberOfProcessors;5354#elif defined(TUKLIB_CPUCORES_SCHED_GETAFFINITY)55cpu_set_t cpu_mask;56if (sched_getaffinity(0, sizeof(cpu_mask), &cpu_mask) == 0)57ret = (uint32_t)CPU_COUNT(&cpu_mask);5859#elif defined(TUKLIB_CPUCORES_CPUSET)60cpuset_t set;61if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1,62sizeof(set), &set) == 0) {63# ifdef CPU_COUNT64ret = (uint32_t)CPU_COUNT(&set);65# else66for (unsigned i = 0; i < CPU_SETSIZE; ++i)67if (CPU_ISSET(i, &set))68++ret;69# endif70}7172#elif defined(TUKLIB_CPUCORES_SYSCTL)73// On OpenBSD HW_NCPUONLINE tells the number of processor cores that74// are online so it is preferred over HW_NCPU which also counts cores75// that aren't currently available. The number of cores online is76// often less than HW_NCPU because OpenBSD disables simultaneous77// multi-threading (SMT) by default.78# ifdef HW_NCPUONLINE79int name[2] = { CTL_HW, HW_NCPUONLINE };80# else81int name[2] = { CTL_HW, HW_NCPU };82# endif83int cpus;84size_t cpus_size = sizeof(cpus);85if (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -186&& cpus_size == sizeof(cpus) && cpus > 0)87ret = (uint32_t)cpus;8889#elif defined(TUKLIB_CPUCORES_SYSCONF)90# ifdef _SC_NPROCESSORS_ONLN91// Most systems92const long cpus = sysconf(_SC_NPROCESSORS_ONLN);93# else94// IRIX95const long cpus = sysconf(_SC_NPROC_ONLN);96# endif97if (cpus > 0)98ret = (uint32_t)cpus;99100#elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)101struct pst_dynamic pst;102if (pstat_getdynamic(&pst, sizeof(pst), 1, 0) != -1)103ret = (uint32_t)pst.psd_proc_cnt;104#endif105106return ret;107}108109110