[Rd] How to safely using OpenMP pragma inside a .C() function?

Simon Urbanek simon.urbanek at r-project.org
Wed Aug 31 23:01:55 CEST 2011


On Aug 31, 2011, at 4:46 PM, pawelm wrote:

> I just found this (performance improvement of the "dist" function when using
> openmp):
> .Internal(setMaxNumMathThreads(1)); .Internal(setNumMathThreads(1)); m <-
> matrix(rnorm(810000),900,900); system.time(d <- dist(m))
>  user  system elapsed 
>  3.510   0.013   3.524 
> .Internal(setMaxNumMathThreads(5)); .Internal(setNumMathThreads(5)); m <-
> matrix(rnorm(810000),900,900); system.time(d <- dist(m));
>   user  system elapsed 
>  3.536   0.007   1.321 
> Works great! Just the question stays if it's a good practice to use
> "R_num_math_threads" in external packages?

Normally you don't need to mess with all this and I would recommend not to do so. The R internals use a different strategy since they need to cope with the fall-back case, but packages should not worry about that. The default number of threads is defined by the OMP_NUM_THREADS environment variable and that is the documented way in OpenMP, so my recommendation would be to not mess with num_threads() which is precisely why I did not use it in the example I gave you.

That said, R-devel has new facilities for parallelization so things may change in the future.


More information about the R-devel mailing list