Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## This a modified version of the example provided in the Rcpp package
- ## from Dirk Eddelbuettel and Romain Francois
- ## in response to the "Julia, I love you" post at:
- ## http://www.johnmyleswhite.com/notebook/2012/03/31/julia-i-love-you/
- require(inline)
- require(compiler)
- ## Rcpp version
- incltxt <- '
- int fibonacci(const int x) {
- if (x == 0) return(0);
- if (x == 1) return(1);
- return (fibonacci(x - 1)) + fibonacci(x - 2);
- }'
- ## now use the snipped above as well as one argument conversion
- ## in as well as out to provide Fibonacci numbers via C++
- fibRcpp <- cxxfunction(signature(xs="int"),
- plugin="Rcpp",
- incl=incltxt,
- body='
- int x = Rcpp::as<int>(xs);
- return Rcpp::wrap( fibonacci(x) );
- ')
- # David J. Harris
- fib2 <- function(n){
- if(n < 2){n}
- else{fib2(n – 1) + fib2(n – 2)}
- }
- # G. Grothendieck
- fib2a <- function(n) {
- if (n < 3) 1
- else {
- y <- rep(1, n)
- for(i in 3:n) y[i] <- {y[i-1] + y[i-2]}
- y[n]
- }
- }
- library(compiler)
- fib2c <- compiler(fib2a)
- ## load rbenchmark to compare
- library(rbenchmark)
- N <- 25
- res <- benchmark(fibRcpp(N),
- fib2(N),
- fib2a(N),
- fib2c(N),
- columns=c("test", "replications", "elapsed",
- "relative"),
- order="relative",
- replications=20)
- print(res) ## show result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement