[R] Programmaticly finding number of processors by R code

Peter Langfelder peter.langfelder at gmail.com
Mon Oct 4 00:17:43 CEST 2010


If no-one replies with a better way, here's a way: under
POSIX-compliant systems, you can write a small C function and wrap it
in an R function.

The C program would be something like

#include <unistd.h>
void nProcessors(int & n)
{
#ifdef _SC_NPROCESSORS_ONLN
  long nProcessorsOnline = sysconf(_SC_NPROCESSORS_ONLN);
#else
  long nProcessorsOnline = 2; // This is my guess - most computers
today have at least 2 cores
#endif
  n = (int) nProcessorsOnline;
}

You need to compile the function into a dynamic library ("shared
object" on linux) and load the dynamic library with dyn.load before
using it.

The R wrapper would be a function along the lines of

nProcessors = function()
{
   n = 0;
   res = .C("nProcessors", n = as.integer(n));
   res$n
}

I haven't actually tested the R function so please take this with a
grain of salt, but I do use the C function in my own C code. You may
also want to read this thread about potential pitfalls and
limitations, plus another (simpler) way that would work on linux:

http://forum.soft32.com/linux2/CPUs-machine-ftopict13343.html

AFAIK, this will not work on Windows because Windows is not POSIX
compliant, but I'm not sure.

Peter


On Sun, Oct 3, 2010 at 10:03 AM, Ajay Ohri <ohri2007 at gmail.com> wrote:
> Dear List
>
> Sorry if this question seems very basic.
>
> Is there a function to pro grammatically find number of processors in
> my system _ I want to pass this as a parameter to snow in some serial
> code to parallel code functions
>
> Regards
>
> Ajay
>



More information about the R-help mailing list