Skip to content

Instantly share code, notes, and snippets.

@FreeSlave
Last active September 22, 2016 13:22
Show Gist options
  • Save FreeSlave/cccd959e9705c714a23a70b3e28439b7 to your computer and use it in GitHub Desktop.
Save FreeSlave/cccd959e9705c714a23a70b3e28439b7 to your computer and use it in GitHub Desktop.
Detecting number of CPU
// Copyright (c) 2016 Roman Chistokhodov
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
#include <stdio.h>
#include <stddef.h>
#if defined(__unix__) || defined(__APPLE__)
#include <unistd.h>
#endif
#ifdef __linux__
#include <sched.h>
#endif
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__)
#include <sys/types.h>
#include <sys/sysctl.h>
#define UseSysctlbyname
#endif
#ifdef _WIN32
#include <windows.h>
#endif
void printFail(const char* methodName)
{
fprintf(stderr, "Could not detect number of CPU using %s\n", methodName);
}
void printSuccess(const char* methodName, int cpuNumber)
{
fprintf(stdout, "Number of CPU according to %s: %d\n", methodName, cpuNumber);
}
int main(int argc, char** argv)
{
#if defined(__unix__) || defined(__APPLE__)
#ifdef _SC_NPROCESSORS_ONLN
long sysconfResult = sysconf(_SC_NPROCESSORS_ONLN);
if (sysconfResult < 1) {
printFail("_SC_NPROCESSORS_ONLN");
} else {
printSuccess("_SC_NPROCESSORS_ONLN", (int)sysconfResult);
}
#else
fprintf(stdout, "_SC_NPROCESSORS_ONLN is not available\n");
#endif
#endif
#ifdef __linux__
#ifdef _GNU_SOURCE
cpu_set_t cs;
CPU_ZERO(&cs);
if (sched_getaffinity(0, sizeof(cs), &cs) != 0) {
printFail("sched_getaffinity");
} else {
int i;
int count = 0;
for (i = 0; i < CPU_COUNT(&cs); i++)
{
if (CPU_ISSET(i, &cs))
count++;
}
printSuccess("CPU_ISSET", count);
}
#else
fprintf(stdout, "Compile with -D_GNU_SOURCE to enable detection via CPU_ISSET\n");
#endif
#endif
#ifdef UseSysctlbyname
#ifdef __APPLE__
const char* name = "machdep.cpu.core_count";
#else
const char* name = "hw.ncpu";
#endif
unsigned int number;
size_t len = sizeof(unsigned int);
sysctlbyname(name, &number, &len, NULL, 0);
if (number < 1) {
printFail("sysctlbyname");
} else {
printSuccess("sysctlbyname", (int)number);
}
#endif
#ifdef _WIN32
SYSTEM_INFO info;
GetSystemInfo(&info);
if (info.dwNumberOfProcessors < 1) {
printFail("GetSystemInfo");
} else {
printSuccess("GetSystemInfo", (int)info.dwNumberOfProcessors);
}
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment