Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
library(Rcpp)
library(microbenchmark)
vectorized <- function() {
a <- c(1, 1)
b <- c(2, 2)
for (i in 1:1000000) {
x <- a + b
}
return()
}
devectorized <- function() {
a <- c(1, 1)
b <- c(2, 2)
for (i in 1:1000000) {
for (index in 1:2) {
x[index] <- a[index] + b[index]
}
}
return()
}
cppFunction('
void rcpp_devectorised() {
NumericVector a = NumericVector::create(1, 1);
NumericVector b = NumericVector::create(2, 2);
NumericVector x(2);
for (int j = 0; j < 1e6; ++j) {
for (int i = 0; i < 2; ++i) {
x[i] = a[i] + b[i];
}
}
}
')
cppFunction('
void rcpp_vectorised() {
NumericVector a = NumericVector::create(1, 1);
NumericVector b = NumericVector::create(2, 2);
NumericVector x(2);
for (int j = 0; j < 1e6; ++j) {
x = a + b;
}
}
')
system.time(vectorized())
# user system elapsed
# 0.526 0.006 0.532
system.time(devectorized())
# user system elapsed
# 8.511 0.012 8.520
microbenchmark(
rcpp_vectorised(),
rcpp_devectorised(),
unit = "s")
# Unit: seconds
# expr min lq median uq max neval
# rcpp_vectorised() 0.012043 0.012308 0.012453 0.012580 0.01319 100
# rcpp_devectorised() 0.000837 0.000848 0.000865 0.000887 0.00101 100
@romainfrancois

This comment has been minimized.

Copy link

@romainfrancois romainfrancois commented May 24, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.