Created
March 8, 2016 09:07
-
-
Save mkuhn/aac1b1e2a2e5f41fa16e to your computer and use it in GitHub Desktop.
Count comparison results without additional memory allocation
This file contains 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) | |
`%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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: