library("Rcpp")
cycle <- cppFunction('
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List fun(NumericVector S) {
R_xlen_t n = S.size();
// Note subsets are 0 indexed, so add -1 to indices
for(R_xlen_t i = 2; i < n; i++) {
S[i] = S[i-1] + S[i-2];
}
return DataFrame::create(Named("S") = S);
}
')
func_r <- function(len) {
S <- rep(0, len)
S[1] <- 0
S[2] <- 1
for (i in 3:length(S)) {
S[i] <- S[i-1] + S[i-2]
}
return(S)
}
func_c <- function(len) {
S <- rep(0, len)
S[1] <- 0
S[2] <- 1
S <- cycle(S)[,1]
return(S)
}
S1 <- func_r(10000)
S2 <- func_c(10000)
all(S1==S2)
microbenchmark::microbenchmark(func_r(100000), func_c(100000), times = 100)