Rcpp Version 1.0.14
Loading...
Searching...
No Matches
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
9suppressMessages(library(Rcpp))
10
11## byte compiler
12require(compiler)
13
14## A C++ version compile with cppFunction
15fibRcpp <- cppFunction( '
16int 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)
25fibR <- 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
32fibRC <- cmpfun(fibR)
33
34## load rbenchmark to compare
35library(rbenchmark)
36
37N <- 35 ## same parameter as original post
38res <- 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)
45print(res) ## show result
46