Skip to content

Instantly share code, notes, and snippets.

@hadley
Forked from Malarkey73/R Vectorisation
Last active January 1, 2016 05:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hadley/8097300 to your computer and use it in GitHub Desktop.
vectorised_r <- function(x, y) {
exp(-abs(x - y))
}
devectorised_r <- function(x, y) {
r <- rep(NA, length(x))
for(i in seq_along(x)) {
r[i] <- exp(-abs(x[i] - y[i]))
}
r
}
library(Rcpp)
cppFunction('NumericVector vectorised_cpp(NumericVector x, NumericVector y) {
return exp(-abs(x - y));
}')
cppFunction('NumericVector devectorised_cpp(NumericVector x, NumericVector y) {
int n = x.size();
NumericVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = exp(-abs(x[i] - y[i]));
}
return out;
}')
# data
x <- 1:2e6
y <- x * 2
# tldr RESULTS !!!!!!!!!!!!!!!!!!
library(microbenchmark)
microbenchmark(
vectorised_r(x, y),
devectorised_r(x, y),
vectorised_cpp(x, y),
devectorised_cpp(x, y),
unit = "s", times = 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment