Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active January 1, 2016 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hadley/8088776 to your computer and use it in GitHub Desktop.
Save hadley/8088776 to your computer and use it in GitHub Desktop.
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
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment