Advertisement
Guest User

Untitled

a guest
Apr 1st, 2012
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## This a modified version of the example provided in the Rcpp package
  2. ## from Dirk Eddelbuettel and Romain Francois
  3. ## in response to the "Julia, I love you" post at:
  4. ## http://www.johnmyleswhite.com/notebook/2012/03/31/julia-i-love-you/
  5.  
  6. require(inline)
  7. require(compiler)
  8.  
  9. ## Rcpp version
  10. incltxt <- '
  11. int fibonacci(const int x) {
  12.   if (x == 0) return(0);
  13.   if (x == 1) return(1);
  14.   return (fibonacci(x - 1)) + fibonacci(x - 2);
  15. }'
  16.  
  17. ## now use the snipped above as well as one argument conversion
  18. ## in as well as out to provide Fibonacci numbers via C++
  19. fibRcpp <- cxxfunction(signature(xs="int"),
  20.                        plugin="Rcpp",
  21.                        incl=incltxt,
  22.                        body='
  23.   int x = Rcpp::as<int>(xs);
  24.   return Rcpp::wrap( fibonacci(x) );
  25. ')
  26.  
  27. # David J. Harris
  28. fib2 <- function(n){
  29.   if(n < 2){n}
  30.   else{fib2(n – 1) + fib2(n – 2)}
  31. }
  32.  
  33. # G. Grothendieck
  34. fib2a <- function(n) {
  35.   if (n < 3) 1
  36.   else {
  37.     y <- rep(1, n)
  38.     for(i in 3:n) y[i] <- {y[i-1] + y[i-2]}
  39.     y[n]
  40.   }
  41. }
  42.  
  43. library(compiler)
  44. fib2c <- compiler(fib2a)
  45.  
  46. ## load rbenchmark to compare
  47. library(rbenchmark)
  48.  
  49. N <- 25
  50. res <- benchmark(fibRcpp(N),
  51.                  fib2(N),
  52.                  fib2a(N),
  53.                  fib2c(N),
  54.                  columns=c("test", "replications", "elapsed",
  55.                           "relative"),
  56.                  order="relative",
  57.                  replications=20)
  58. print(res)  ## show result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement