[R-sig-hpc] Looking for some function to determine how many cores I have

Dirk Eddelbuettel edd at debian.org
Fri Aug 5 02:38:24 CEST 2011


On 4 August 2011 at 09:38, Megh Dal wrote:
| Dear all, I am looking for some R function which will tell me how many cores I have in my machine. I am using Windows Vista and snowfall library for my parallel computations. However I need to automate the initializing the parallel computation using sfInit() function, for which number of cores is one input.
| 
| I can personally see the core numbers from Windows Task Manager, however want to automate (in some extend) my calculation. Is there any function to determine that number?

Brian Ripley is currently adding a new package 'parallel' to the R-devel SVN;
this should be part of R 2.14.0 due October.

It has a function to do this, but the code it pretty OS-dependent. Here is
the R function R/detectCores.R :


if(.Platform$OS.type == "windows") {
detectCores <- function(all.tests = FALSE)
    .Call("ncpus", FALSE, package = "parallel")
} else {
detectCores <- function(all.tests = FALSE)
{
    systems <-
        list(darwin  = "/usr/sbin/sysctl -n hw.ncpu 2>/dev/null",
             freebsd = "/sbin/sysctl -n hw.ncpu 2>/dev/null",
             linux   = "grep processor /proc/cpuinfo 2>/dev/null | wc -l",
             irix    = c("hinv | grep Processors | sed 's: .*::'",
                         "hinv | grep '^Processor '| wc -l"),
#             solaris = "/usr/sbin/psrinfo -v | grep 'Status of.*processor' | wc -l"
             solaris = "/usr/sbin/psrinfo -p")
    for (i in seq(systems))
        if(all.tests ||
           length(grep(paste("^", names(systems)[i], sep=''), R.version$os)))
            for (cmd in systems[i]) {
                a <- gsub("^ +","", system(cmd, TRUE)[1])
                if (length(grep("^[1-9]", a))) return(as.integer(a))
            }
    NA_integer_
}
}


and on Windows you have to build and execute this C function src/ncpus.c:

#include <R.h>
#include "parallel.h"

#define WIN32_LEAN_AND_MEAN
#include <windows.h>


SEXP ncpus(SEXP virtual)
{
    int virt = asLogical(virtual);
    SYSTEM_INFO info;
    GetSystemInfo(&info);
    int nc = info.dwNumberOfProcessors;
    return ScalarInteger(nc);
}



Dirk


-- 
Gauss once played himself in a zero-sum game and won $50.
                      -- #11 at http://www.gaussfacts.com



More information about the R-sig-hpc mailing list