Skip to content

Instantly share code, notes, and snippets.

@mkuhn
Created March 8, 2016 09:07
Show Gist options
  • Save mkuhn/aac1b1e2a2e5f41fa16e to your computer and use it in GitHub Desktop.
Save mkuhn/aac1b1e2a2e5f41fa16e to your computer and use it in GitHub Desktop.
Count comparison results without additional memory allocation
library(Rcpp)
`%count<%` <- cppFunction('
size_t count_less(NumericVector x, NumericVector y) {
const size_t nx = x.size();
const size_t ny = y.size();
if (nx > 1 & ny > 1) stop("Only one parameter can be a vector!");
size_t count = 0;
if (nx == 1) {
double c = x[0];
for (int i = 0; i < ny; i++) count += c < y[i];
} else {
double c = y[0];
for (int i = 0; i < nx; i++) count += x[i] < c;
}
return count;
}
')
set.seed(42)
N <- 100000000
v <- runif(N, 0, 10000)
system.time(sum(v < 5000))
system.time(v %count<% 5000)
@mkuhn
Copy link
Author

mkuhn commented Mar 8, 2016

Results:

> system.time(sum(v < 5000))
   user  system elapsed 
  0.488   0.115   0.605 
> system.time(v %count<% 5000)
   user  system elapsed 
  0.065   0.000   0.065 

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