gpt4 book ai didi

r - R vs Rcpp 中的斐波那契数

转载 作者:行者123 更新时间:2023-12-02 06:28:29 24 4
gpt4 key购买 nike

我只是想检查 R 与 Rcpp 中斐波那契数生成的执行速度。令我惊讶的是,我的 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);
}

最佳答案

您的 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)

关于r - R vs Rcpp 中的斐波那契数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48145336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com