I wrote an R code to calculate the tail sum of a vector:
tailsum <- function(x){
sum(x) + x - cumsum(x)
}
I hope to improve the efficiency of this function through RcppArmadillo, so I wrote
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <Rcpp.h>
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
colvec tailsum_arma(const colvec &x){
return sum(x) + x - cumsum(x);
}
NumericVector cumsum_self(const NumericVector &x){
auto x_len = x.length();
NumericVector y(x_len);
y[0] = x[0];
for(int i = 1;i < x_len; i++){
y[i] = y[i - 1] + x[i];
}
return y;
}
// [[Rcpp::export]]
NumericVector tailsum_cpp(const NumericVector &x){
//just to compare with tailsum_arma
return sum(x) + x - cumsum_self(x);
}
But to my surprise, R code is more efficient than RcppArmadillo code:
> x <- rnorm(1000)
> microbenchmark(
+ tailsum(x),
+ tailsum_cpp(x),
+ tailsum_arma(x)
+ )
Unit: microseconds
expr min lq mean median uq max neval cld
tailsum(x) 2.0 2.3 2.826 2.5 2.70 14.4 100 a
tailsum_cpp(x) 1.9 2.1 2.495 2.3 2.60 6.5 100 a
tailsum_arma(x) 2.2 2.4 3.128 2.6 2.85 30.4 100 a
How can I improve my code written in RcppArmadillo?(I need to use RcppArmadillo because there are many other linear algebra operations that are done using RcppArmadillo.)