Skip to main content

R and C++ integration: my first baby steps using inline

Hi,
Really excited to try out stuff in Dirk's book. The first chapter of the book gives a gentle introduction to Rcpp and inline package. The problem setting is how to integrate a fibonacci recursive function in C++, compile it and execute it in R. Benchmarking results are also shown.
The program code is all below in one R file. Its the same code in the book under listing 1.2

library(inline)
library(rbenchmark)
library(Rcpp)
#inline function for fibonacci algorithm in C++
incltxt <- '
int fibonacci(const int x) {
  if (x == 0) return(0);
if (x == 1) return(1);
  return fibonacci(x - 1) + fibonacci(x - 2);
}'
#wrapper function
fibRcpp <- cxxfunction(signature(xs="int"),
                       plugin="Rcpp",
                       incl=incltxt,
                        body='
                        int x = Rcpp::as<int>(xs);
                        return Rcpp::wrap( fibonacci(x) );
                       ')
#R function implementation the fibonacci algorithm
fibR <- function(n)
{
  if(n == 0) return(0)
  if(n == 1) return(1)
  return (fibR(n - 1) + fibR(n - 2))
}
#benchmark the R function call
a <- proc.time()
fibR(30)
proc.time() - a
#benchmark the R function call
benchR <- benchmark(replications = 1, fibR(30), columns = c('test','elapsed'))
#Benchmark the cpp function call
benchRCpp <- benchmark(replications = 1, fibRcpp(30), columns = c('test','elapsed'))
#How fast was it? About 200 times!!
(benchR$elapsed/benchRCpp$elapsed)

I was running this on an XP core2Duo machine and got a 200 times speed up. Yes I am poor and this is the best I can afford at the time but wow thats cool.

Anyway when I tried to compile the inline and the wrapper function I got some errors which looked like this.
Error in compileCode(f, code, language = language, verbose = verbose)
After going thru some of the posts on the topic I figured it had to do with the compiler I was using. My machine had a PATH variable with a Borland Cpp path which was causing the MAKE function in the R(C++) compiler to fall over.
I solved this by doing the following as R depends on the gcc compiler. Mind you this is for Windows.

  • Install the RTools in a directory. Usually this gets installed if you want to code in cpp in RStudio as it asks by default. Anyway you can install it independently.
  • Once installed, open command line by Run -> cmd
  • The Rtools directory may look something like this "C:\RBuildTools\3.1"
  • In the cmd prompt type PATH = %PATH%;C:\RBuildTools\3.1\bin;C:\RBuildTools\3.1\gcc-4.6.3\bin
  • Your good to go from there
  • Remember to remove the reference to other compilers and you will be able to compile the code above.
  • Sweet.

Comments