-
-
Save romainfrancois/8093277 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment