Fibonacci number in R vs Rcpp

微笑、不失礼 提交于 2019-12-10 22:34:41

问题


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);
}

回答1:


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)



来源:https://stackoverflow.com/questions/48145336/fibonacci-number-in-r-vs-rcpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!