R与Rcpp中的斐波纳契数

时间:2018-01-08 06:34:41

标签: r rcpp

我只是想检查R与Rcpp中Fiboncci数字生成的执行速度。令我惊讶的是,我的R函数比我的Rcpp函数更快(也是线性增长)。这里有什么问题。

R代码:

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

Rcpp代码:

#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 个答案:

答案 0 :(得分:7)

您的Rcpp代码的问题在于您正在增长向量而不是在开头分配大小。试试:

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

基准:

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:检查你的第一个值

PS2:注意大数字(见this