Rcpp Version 1.0.9
fibonacci.r
Go to the documentation of this file.
1 #!/usr/bin/env r
2 
3 ## this short example was provided in response to this StackOverflow questions:
4 ## http://stackoverflow.com/questions/6807068/why-is-my-recursive-function-so-slow-in-r
5 ## and illustrates that recursive function calls are a) really expensive in R and b) not
6 ## all expensive in C++ (my machine sees a 700-fold speed increase) and c) the byte
7 ## compiler in R does not help here.
8 
9 suppressMessages(library(Rcpp))
10 
11 ## byte compiler
12 require(compiler)
13 
14 ## A C++ version compile with cppFunction
15 fibRcpp <- cppFunction( '
16 int fibonacci(const int x) {
17  if (x == 0) return(0);
18  if (x == 1) return(1);
19  return (fibonacci(x - 1)) + fibonacci(x - 2);
20 }
21 ' )
22 
23 
24 ## for comparison, the original (but repaired with 0/1 offsets)
25 fibR <- function(seq) {
26  if (seq == 0) return(0);
27  if (seq == 1) return(1);
28  return (fibR(seq - 1) + fibR(seq - 2));
29 }
30 
31 ## also use byte-compiled R function
32 fibRC <- cmpfun(fibR)
33 
34 ## load rbenchmark to compare
35 library(rbenchmark)
36 
37 N <- 35 ## same parameter as original post
38 res <- benchmark(fibR(N),
39  fibRC(N),
40  fibRcpp(N),
41  columns=c("test", "replications", "elapsed",
42  "relative", "user.self", "sys.self"),
43  order="relative",
44  replications=1)
45 print(res) ## show result
46