stay with problems longer

R with C++

|

R에서 C++ 활용하기

C++ 함수의 간단한 활용법에 대해서 알아보자. Rcpp 패키지를 설치한 후에 CppFunction안에 간단한 C++ 소스를 작성한다.

if (!require(Rcpp)) install.packages("Rcpp")
if (!require(Rcpp)) install.packages("microbenchmark")
cppFunction("
            int add(int x, int y, int z) {
              int sum = x + y + z;
              return sum;
            }
            ")
add
## function (x, y, z) 
## .Call(<pointer: 0x7fb345196f80>, x, y, z)
add(1, 2, 3)
## [1] 6

sourceCpp의 사용

독립적인 C++파일을 사용하고 sourceCpp()로 소스를 R에 로드하는 것이 더 쉽다. (C++파일은 .cpp 확장자를 가진다.)

sourceCpp(code = "
          #include <Rcpp.h>
          using namespace Rcpp;
          
          // [[Rcpp::export]]
          double meanC(NumericVector x) {
            int n = x.size();
            double total = 0;
            
            for (int i = 0; i < n; ++i) {
              total += x[i];
            }
            return total / n;
          }
          ")

x <- runif(1e5)
microbenchmark(
  mean(x),
  meanC(x)
)
## Unit: microseconds
##      expr     min       lq     mean   median       uq       max neval cld
##   mean(x) 165.501 165.6705 168.0164 165.7930 166.9275   294.588   100   a
##  meanC(x) 110.170 110.3185 221.8499 110.5475 111.3360 11179.855   100   a
  • 출처: ‘Advanced R by Hadley Wickham’

Comments