From f0b3cb1845b06d673d232651c25a279fbeb09c4c Mon Sep 17 00:00:00 2001
From: Vadim Pisarevsky <no@email>
Date: Tue, 2 Aug 2011 12:42:58 +0000
Subject: [PATCH] added getNumberOfCPUs() function

---
 modules/core/include/opencv2/core/core.hpp |  3 ++
 modules/core/src/system.cpp                | 42 ++++++++++++++++++++++
 2 files changed, 45 insertions(+)

diff --git a/modules/core/include/opencv2/core/core.hpp b/modules/core/include/opencv2/core/core.hpp
index 11e8124de..9686586f9 100644
--- a/modules/core/include/opencv2/core/core.hpp
+++ b/modules/core/include/opencv2/core/core.hpp
@@ -263,6 +263,9 @@ CV_EXPORTS_W int64 getCPUTickCount();
 */
 CV_EXPORTS_W bool checkHardwareSupport(int feature);
 
+//! returns the number of CPUs (including hyper-threading)
+CV_EXPORTS_W int getNumberOfCPUs();
+    
 /*!
   Allocates memory buffer
   
diff --git a/modules/core/src/system.cpp b/modules/core/src/system.cpp
index bdd44d292..32b152f34 100644
--- a/modules/core/src/system.cpp
+++ b/modules/core/src/system.cpp
@@ -85,6 +85,13 @@
 
 #include <stdarg.h>
 
+#if defined __linux__ || defined __APPLE__
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/types.h> 
+#include <sys/sysctl.h>
+#endif
+
 namespace cv
 {
 
@@ -365,6 +372,41 @@ int getThreadNum(void)
 #endif
 }
 
+int getNumberOfCPUs(void)
+{
+#if defined WIN32 || defined _WIN32
+    SYSTEM_INFO sysinfo;
+    GetSystemInfo( &sysinfo );
+    
+    return (int)sysinfo.dwNumberOfProcessors;
+#elif defined __linux__
+    return (int)sysconf( _SC_NPROCESSORS_ONLN );
+#elif defined __APPLE__
+    int numCPU=0;
+    int mib[4];
+    size_t len = sizeof(numCPU); 
+    
+    /* set the mib for hw.ncpu */
+    mib[0] = CTL_HW;
+    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;
+    
+    /* get the number of CPUs from the system */
+    sysctl(mib, 2, &numCPU, &len, NULL, 0);
+    
+    if( numCPU < 1 ) 
+    {
+        mib[1] = HW_NCPU;
+        sysctl( mib, 2, &numCPU, &len, NULL, 0 );
+        
+        if( numCPU < 1 )
+            numCPU = 1;
+    }
+    
+    return (int)numCPU;
+#else
+    return 1;
+#endif
+}
 
 string format( const char* fmt, ... )
 {