Skip to content

Instantly share code, notes, and snippets.

@hadley
Created November 9, 2012 21:09
Show Gist options
  • Select an option

  • Save hadley/4048250 to your computer and use it in GitHub Desktop.

Select an option

Save hadley/4048250 to your computer and use it in GitHub Desktop.
library(Rcpp)
cppFunction('
NumericVector my_diff(NumericVector x, const int lag) {
NumericVector y(x.length() - lag);
int n = x.length();
for (int i = lag; i < n; i++) {
y[i - lag] = x[i] - x[i - lag];
}
return(y);
}'
)
x <- as.numeric(sample(10, 1e4, rep = T))
library(microbenchmark)
microbenchmark(
diff(x, 1),
my_diff(x, 1))
# About ten times faster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment