Madhuresh
Madhuresh

Reputation: 49

Fibonacci number in R vs Rcpp

I was just trying to check the execution speed of Fiboncci number generation in R vs Rcpp. To my surprise, my R function was faster(also, linearly growing) than my Rcpp function. What is wrong here.

The R code:

fibo = function (n){
    x = rep(0, n)
    x[1] = 1
    x[2] = 2

    for(i in 3:n){
        x[i] = x[i-2] + x[i-1]
    }
    return(x)
}

The Rcpp code:

#include <Rcpp.h>

using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector fibo_sam(int n){
    IntegerVector x;
    x.push_back(1);
    x.push_back(2);
    for(int i =2; i < n; i++){
        x.push_back(x[i - 2] + x[i-1]);
    }
    return(x);
}

Upvotes: 2

Views: 250

Answers (1)

F. Priv&#233;
F. Priv&#233;

Reputation: 11728

The problem with your Rcpp code is that you are growing the vector instead of allocating the size at the beginning. Try with:

// [[Rcpp::export]]
IntegerVector fibo_sam2(int n) {
  IntegerVector x(n);
  x[0] = 1;
  x[1] = 2;
  for (int i = 2; i < n; i++){
    x[i] = x[i-2] + x[i-1];
  }
  return(x);
}

Benchmark:

Unit: microseconds
            expr     min       lq      mean  median       uq      max neval cld
      fibo(1000)  99.989 102.6375 157.42543 103.962 106.9415 4806.395   100  a 
  fibo_sam(1000) 493.320 511.8615 801.39046 534.044 590.4945 2825.168   100   b
 fibo_sam2(1000)   2.980   3.3110  10.18763   3.642   4.3040  573.443   100  a 

PS1: check your first values

PS2: beware large numbers (see this)

Upvotes: 9

Related Questions