All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
ncores.cc
Go to the documentation of this file.
1 #include "osl/misc/ncores.h"
2 #include "osl/oslConfig.h"
3 #include <cassert>
4 #include <algorithm>
5 #include <iostream>
6 
7 #if defined(__linux)
8 # include <unistd.h>
9 #elif defined(__APPLE__)
10 # include <mach/mach.h>
11 # include <mach/machine.h>
12 #elif defined(__FreeBSD__)
13 # include <sys/types.h>
14 # include <sys/sysctl.h>
15 # include <unistd.h>
16 #elif defined(_WIN32)
17 # include <windows.h>
18 #endif
19 
20 int osl::misc::
21 ncores() {
22  int cpuCount = 1;
23 
24 #if defined(__linux)
25  cpuCount = sysconf(_SC_NPROCESSORS_ONLN);
26 #elif defined(__APPLE__)
27  kern_return_t kr;
28  struct host_basic_info hostinfo;
29  mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
30  kr = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostinfo, &count);
31  if(kr == KERN_SUCCESS) {
32  cpuCount = hostinfo.avail_cpus;
33  }
34 #elif defined( __FreeBSD__)
35  cpuCount = sysconf(_SC_NPROCESSORS_ONLN);
36 #elif defined(_WIN32)
37  {
38  typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
39  SYSTEM_INFO si;
40  PGNSI pGNSI = NULL;
41 # ifndef __MINGW32__
42  pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),
43  "GetNativeSystemInfo"); // The system frees it.
44 # endif
45  if(NULL != pGNSI){
46  pGNSI(&si);
47  }else{
48  GetSystemInfo(&si);
49  }
50  cpuCount = si.dwNumberOfProcessors;
51  }
52 #else
53  std::cerr << "Unknown #cores. Use the default value: " << cpuCount << "\n";
54 #endif
55 
56  assert(cpuCount > 0);
57  if (cpuCount > OslConfig::MaxThreads)
58  std::cerr << "cpuCount " << cpuCount << " > " << "MaxThreads " << OslConfig::MaxThreads << "\n";
59  return std::min(cpuCount, OslConfig::MaxThreads);
60 }
61 
62 /*
63  * Alternative is
64  * <sched.h>
65  * CPU_COUNT (cpusetp)
66  * It is available for glibc 2.6
67  * See http://www.nabble.com/-gomp--Speed-up-and-improve-CPU-number-checking-t3681303.html
68  *
69  */
70 
71 /* ------------------------------------------------------------------------- */
72 // ;;; Local Variables:
73 // ;;; mode:c++
74 // ;;; c-basic-offset:2
75 // ;;; End:
76