[R] Number of CPU's

Ei-ji Nakama nakama at ki.rim.or.jp
Wed Aug 26 03:54:11 CEST 2009


Hi

Please preserve as get_num_cpus.c as follows.
---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8----
#include <unistd.h>
#include <stdlib.h>
#ifdef WIN32
#include <windows.h>
#endif
#include <R.h>
#include <Rdefines.h>
SEXP get_num_cpus(void)
{
    SEXP cpus;
    PROTECT (cpus = allocVector (INTSXP, 1));
    INTEGER(cpus)[0]=1;
#ifdef _SC_NPROCESSORS_ONLN
    {
	/* MacOSX, Linux, Solaris, AIX */
	INTEGER(cpus)[0] = sysconf(_SC_NPROCESSORS_ONLN);
    }
#else
#  ifdef WIN32
    {
	/* Windows */
	DWORD processAffinityMask;
	DWORD systemAffinityMask;
 	
	if (GetProcessAffinityMask( GetCurrentProcess(),
				    &processAffinityMask,
				    &systemAffinityMask)){
	    processAffinityMask = (processAffinityMask & 0x55555555)
		+ (processAffinityMask >> 1 & 0x55555555);
	    processAffinityMask = (processAffinityMask & 0x33333333)
		+ (processAffinityMask >> 2 & 0x33333333);
	    processAffinityMask = (processAffinityMask & 0x0f0f0f0f)
		+ (processAffinityMask >> 4 & 0x0f0f0f0f);
	    processAffinityMask = (processAffinityMask & 0x00ff00ff)
		+ (processAffinityMask >> 8 & 0x00ff00ff);
	    INTEGER(cpus)[0]     = (processAffinityMask & 0x0000ffff)
		+ (processAffinityMask >>16 & 0x0000ffff);
	}
    }
#  endif	
#endif
    UNPROTECT (1);
    return cpus;
}
---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8----

$ R CMD SHLIB get_num_cpus.c
$ R -q
> dyn.load(paste("get_num_cpus", .Platform$dynlib.ext, sep=""))
> .Call("get_num_cpus")
[1] 2

You obtain the number of CPU core.

2009/8/25 Håvard Rue <Havard.Rue at math.ntnu.no>:
> Any way to get access to the number of CPU's, optionally their type,
> from within  R?   In linux I can just read /proc/cpuinfo  but for
> win/mac ?
>
> Thanks!
> Håvard
>
> --
>  Håvard Rue
>  Department of Mathematical Sciences
>  Norwegian University of Science and Technology
>  N-7491 Trondheim, Norway
>  Voice: +47-7359-3533    URL  : http://www.math.ntnu.no/~hrue
>  Fax  : +47-7359-3524    Email: havard.rue at math.ntnu.no
>
>  This message was created in a Microsoft-free computing environment.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
EI-JI Nakama  <nakama (a) ki.rim.or.jp>
"\u4e2d\u9593\u6804\u6cbb"  <nakama (a) ki.rim.or.jp>




More information about the R-help mailing list