Should I use Rcpp :: NumericVector via std :: vector?

Is there any reason why I should prefer Rcpp::NumericVectorover std::vector<double>?

For example, two functions below

// [[Rcpp::export]]
Rcpp::NumericVector foo(const Rcpp::NumericVector& x) {
  Rcpp::NumericVector tmp(x.length());
  for (int i = 0; i < x.length(); i++)
    tmp[i] = x[i] + 1.0;
  return tmp;
}

// [[Rcpp::export]]
std::vector<double> bar(const std::vector<double>& x) {
  std::vector<double> tmp(x.size());
  for (int i = 0; i < x.size(); i++)
    tmp[i] = x[i] + 1.0;
  return tmp;
}

They are equivalent when considering their performance and benchmarks. I understand that Rcpp offers work with sugar and vectorized operations, but if it is only about taking the vector R as the input and return vector as the output, will there be any difference which one I use? Can use std::vector<double>lead to any possible problems when interacting with R?

+2
source share
2 answers

They are equivalent when considering their performance and benchmarks.

  • , , SEXP std::vector<double> . ( , @DirkEddelbuettel .)
  • Rcpp (, const Rcpp::NumericVector& x) - . , , (. ). , , const std::vector<double>& x, "" " ".

std::vector<double> R?

, . , , - .

- , a NumericVector, NumericVector, . , std::vector<T> . :

#include<Rcpp.h>

// [[Rcpp::export]]
void test_copy(){
    NumericVector A = NumericVector::create(1, 2, 3);
    NumericVector B = A;

    Rcout << "Before: " << std::endl << "A: " << A << std::endl << "B: " << B << std::endl; 

    A[1] = 5; // 2 -> 5

    Rcout << "After: " << std::endl << "A: " << A << std::endl << "B: " << B << std::endl; 
}

:

test_copy()
# Before: 
# A: 1 2 3
# B: 1 2 3
# After: 
# A: 1 5 3
# B: 1 5 3

- , Rcpp::NumericVector std::vector<double>?

:

  • , Rcpp::NumericVector ++ std::vector<T>.
  • .
  • "" Rcpp ++ (, .attr())
+6

" , ."

, , , :

/*** R
library(microbenchmark)
x <- 1.0* 1:1e7   # make sure it is numeric
microbenchmark(foo(x), bar(x), times=100L)
*/

sourceCpp("...yourfile...") ( / ):

R> library(microbenchmark)

R> x <- 1.0* 1:1e7   # make sure it is numeric

R> microbenchmark(foo(x), bar(x), times=100L)
Unit: milliseconds
   expr     min      lq    mean  median      uq      max neval cld
 foo(x) 31.6496 31.7396 32.3967 31.7806 31.9186  54.3499   100  a 
 bar(x) 50.9229 51.0602 53.5471 51.1811 51.5200 147.4450   100   b
R> 

bar() R R-. foo() . , . 1,8.

, ..

+5

Source: https://habr.com/ru/post/1694854/


All Articles