/*      ncpus.cpp
//
//      Copyright 2005-2011 Lucas Tsatiris <systester.project@gmail.com>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
//
*/


/*
 *  Find the number of the active CPUs
 *
 */

#if !defined(NCPUS)
#define NCPUS

#if defined (__linux) || defined (__osf__) || defined (__hpux) || defined (__sun)
#include <unistd.h>
#if defined (__hpux)
#include <sys/mpctl.h>
#endif /* __hpux */
#elif defined (__APPLE__)
#include <sys/types.h>
#include <sys/sysctl.h>
#elif defined (_MSC_VER) || defined (__MINGW32__)
#include <windows.h>
#endif /* __linux || __osf__ ... */


int
ncpus ()
{
  int cpus = 1;

#if defined (__linux) || defined (__osf__) || defined (__sun) || defined (_AIX)
  cpus = sysconf (_SC_NPROCESSORS_ONLN);
#elif defined (__hpux)
  cpus = mpctl (MPC_GETNUMSPUS, (spu_t) 0, (pid_t) 0);
#elif defined (__APPLE__)
  size_t len = sizeof (cpus);
  sysctl ((int[2])
	  {
	  CTL_HW, HW_NCPU}, 2, &cpus, &len, NULL, 0);
#elif defined (_MSC_VER) || defined (__MINGW32__)
  DWORD_PTR process_cpus;
  DWORD_PTR system_cpus;
  if (GetProcessAffinityMask
      (GetCurrentProcess (), &process_cpus, &system_cpus))

    {
      int count;
      for (count = 0; process_cpus != 0; process_cpus >>= 1)
	if (process_cpus & 1)
	  count++;
      cpus = count;
    }
#endif /* defined(__linux) ... */
  return cpus;
}

#endif /* NCPUS */
