public
Last active

Comparison of binary matrix algorithms (minus the Rcpparmadillo versions).

  • Download Gist
binmat_comparison.r
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
library(inline); library(compiler); library(rbenchmark)
 
n <- 500
k <- 100
 
scott <- function(N, K) {
mm <- matrix(0, N, K)
apply(mm, c(1, 2), function(x) sample(c(0, 1), 1))
}
scottComp <- cmpfun(scott)
 
ted <- function(N, K) {
matrix(rbinom(N * K, 1, 0.5), ncol = K, nrow = N)
}
 
david <- function(m, n) {
matrix(sample(0:1, m * n, replace = TRUE), m, n)
}
 
luis <- function(m, n) {
round(matrix(runif(m * n), m, n))
}
 
josh <- function(m, n) {
x <- sample.int(2, m*n, TRUE)-1L
dim(x) <- c(m,n)
x
}
 
sugar <- cxxfunction(signature(ns="integer", ks="integer"), plugin = "Rcpp", body='
int n = Rcpp::as<int>(ns);
int k = Rcpp::as<int>(ks);
Rcpp::RNGScope tmp;
Rcpp::NumericVector draws = Rcpp::runif(n*k);
return Rcpp::NumericMatrix(n, k, draws.begin());
')
 
sugarFloor <- cxxfunction(signature(ns="integer", ks="integer"), plugin = "Rcpp", body='
int n = Rcpp::as<int>(ns);
int k = Rcpp::as<int>(ks);
Rcpp::RNGScope tmp;
Rcpp::NumericVector draws = Rcpp::floor(Rcpp::runif(n*k)+0.5);
return Rcpp::NumericMatrix(n, k, draws.begin());
')
 
res <- benchmark(scott(n, k), scottComp(n,k),
ted(n, k), david(n, k), luis(n, k), josh(n, k),
sugar(n,k), sugarFloor(n, k),
order="relative", replications=100)
 
> print(res[,1:4])
test replications elapsed relative
7 sugar(n, k) 100 0.113 1.000
6 josh(n, k) 100 0.124 1.097
8 sugarFloor(n, k) 100 0.147 1.301
4 david(n, k) 100 0.190 1.681
3 ted(n, k) 100 0.375 3.319
5 luis(n, k) 100 0.462 4.088
1 scott(n, k) 100 54.378 481.221
2 scottComp(n, k) 100 56.330 498.496

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.