Created
September 5, 2012 16:44
-
-
Save sckott/3639688 to your computer and use it in GitHub Desktop.
Comparison of binary matrix algorithms (minus the Rcpparmadillo versions).
This file contains hidden or 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(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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment