Rcpp Version 0.12.12
newFib.r
Go to the documentation of this file.
1 #!/usr/bin/env r
2 
3 ## New and shorter version of Fibonacci example using Rcpp 0.9.16 or later features
4 ## The the sibbling file 'fibonacci.r' for context
5 
6 require(Rcpp) # no longer need inline
7 
8 ## R version
9 fibR <- function(seq) {
10  if (seq < 2) return(seq)
11  return (fibR(seq - 1) + fibR(seq - 2))
12 }
13 
14 ## C++ code
15 cpptxt <- '
16 int fibonacci(const int x) {
17  if (x < 2) return(x);
18  return (fibonacci(x - 1)) + fibonacci(x - 2);
19 }'
20 
21 ## C++ version
22 fibCpp <- cppFunction(cpptxt) # compiles, load, links, ...
23 
24 ## load rbenchmark to compare
25 library(rbenchmark)
26 
27 N <- 35 ## same parameter as original post
28 res <- benchmark(fibR(N), fibCpp(N),
29  columns=c("test", "replications", "elapsed", "relative"),
30  order="relative", replications=1)
31 print(res) ## show result
32