ncores.cc
Go to the documentation of this file.
00001 #include "osl/misc/ncores.h"
00002 #include "osl/oslConfig.h"
00003 #include <cassert>
00004 #include <algorithm>
00005 #include <iostream>
00006 
00007 #if defined(__linux)
00008 #   include <unistd.h>
00009 #elif defined(__APPLE__)
00010 #   include <mach/mach.h>
00011 #   include <mach/machine.h>
00012 #elif defined(__FreeBSD__)
00013 #   include <sys/types.h>
00014 #   include <sys/sysctl.h>
00015 #   include <unistd.h>
00016 #elif defined(_WIN32)
00017 #   include <windows.h>
00018 #endif
00019 
00020 int osl::misc::
00021 ncores() {
00022   int cpuCount = 1;
00023 
00024 #if defined(__linux)
00025   cpuCount = sysconf(_SC_NPROCESSORS_ONLN);
00026 #elif defined(__APPLE__)
00027   kern_return_t kr;
00028   struct host_basic_info hostinfo;
00029   mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
00030   kr = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostinfo, &count);
00031   if(kr == KERN_SUCCESS) {
00032     cpuCount = hostinfo.avail_cpus;
00033   }
00034 #elif defined( __FreeBSD__)
00035   cpuCount = sysconf(_SC_NPROCESSORS_ONLN);
00036 #elif defined(_WIN32)
00037   {
00038     typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
00039     SYSTEM_INFO si;
00040     PGNSI pGNSI = NULL;
00041 #   ifndef __MINGW32__
00042     pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),  
00043                                   "GetNativeSystemInfo"); // The system frees it.
00044 #   endif
00045     if(NULL != pGNSI){
00046         pGNSI(&si);
00047     }else{
00048         GetSystemInfo(&si);
00049     }
00050     cpuCount = si.dwNumberOfProcessors;
00051   }
00052 #else
00053   std::cerr << "Unknown #cores. Use the default value: " << cpuCount << "\n";
00054 #endif
00055 
00056   assert(cpuCount > 0);
00057   if (cpuCount > OslConfig::MaxThreads)
00058     std::cerr << "cpuCount " << cpuCount << " > " << "MaxThreads " << OslConfig::MaxThreads << "\n";
00059   return std::min(cpuCount, OslConfig::MaxThreads);
00060 }
00061 
00062 /*
00063  * Alternative is
00064  *   <sched.h>
00065  *   CPU_COUNT (cpusetp)
00066  * It is available for glibc 2.6
00067  * See http://www.nabble.com/-gomp--Speed-up-and-improve-CPU-number-checking-t3681303.html
00068  *
00069  */
00070 
00071 /* ------------------------------------------------------------------------- */
00072 // ;;; Local Variables:
00073 // ;;; mode:c++
00074 // ;;; c-basic-offset:2
00075 // ;;; End:
00076 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines