library(Rcpp)

cppFunction('Rcpp::NumericVector sum_vectors_C(NumericVector x, NumericVector y) {
  int n = x.size();

  Rcpp::NumericVector total(x.size());

  for(int i = 0; i < n; ++i) {
    total[i] = x[i] + y[i];
  }
  return total;
}')

x <- runif(100)
y <- runif(100)

sol_C <- sum_vectors_C(x, y)
sol_R <- x + y

identical(sol_C, sol_R)

library(tictoc)

tic('Using Rcpp')
sol_C <- sum_vectors_C(x, y)
toc()

tic('Using base R')
sol_R <- x + y
toc()

tic('Using a loop and prealocation')
sol_loop <- numeric(length = length(x))
for (i in 1:length(x)) {
  sol_loop[i] <- x[i] + y[i]
}
toc()
# none
#my_answers <- make_random_answers(my_sol)
my_answers <- rep(NA, 5)

type_question <- 'string'
ex_name <- 'otimizing 13-03'

Question

Use the tictoc package to compare the performance of the previous function with the native operator +, and a loop-based version with the pre-allocation of the result vector. Which alternative has the shortest execution time and why? Does the Rcpp version beat the loop version?

Solution

The best way to add vectors is with the native operator +, which is already optimized for fast executions.


Meta-information

extype: r type_question exsolution: r mchoice2string(c(TRUE, FALSE, FALSE, FALSE, FALSE), single = TRUE) exname: r ex_name exshuffle: TRUE



msperlin/afedR documentation built on Sept. 11, 2022, 9:49 a.m.