ใช้ OpenMP กับ Rcpp

ที่มา https://github.com/RcppCore/Rcpp/blob/master/inst/examples/OpenMP/OpenMPandInline.r

ตัวอย่าง Rcpp กับ OpenMP

library(inline)

openMPCode <- ‘

// assign to C++ vector

std::vector<double> x = Rcpp::as<std::vector< double > >(xs);

size_t n = x.size();

#pragma omp parallel for shared(x, n)

for (size_t i=0; i<n; i++) {

x[i] = ::log(x[i]);

}

return Rcpp::wrap(x);

settings <- getPlugin("Rcpp")
settings$env$PKG_CXXFLAGS <- paste('-fopenmp', settings$env$PKG_CXXFLAGS)
settings$env$PKG_LIBS <- paste('-fopenmp -lgomp', settings$env$PKG_LIBS)

funOpenMP <- cxxfunction(signature(xs="numeric"), body=openMPCode, plugin="Rcpp", settings=settings)

z <- seq(1, 2e6)

funOpenMP(z)

Tags:,