Skip to content

Instantly share code, notes, and snippets.

@chenpanliao
Created September 8, 2022 02:14
Show Gist options
  • Save chenpanliao/afd4b28f99d5d2e8ec240b10827114a5 to your computer and use it in GitHub Desktop.
Save chenpanliao/afd4b28f99d5d2e8ec240b10827114a5 to your computer and use it in GitHub Desktop.
library(rbenchmark)
library(Matrix)
ncol <- 2e3
nrow <- 1e3
x <- matrix(rbinom(ncol * nrow, 1, 0.1), nrow = nrow, ncol = ncol)
benchmark(
which(x != 0, arr.ind = T), # method 0
which(Matrix(x, sparse = T) != 0, arr.ind = T), # method 1
Matrix(x, sparse = T) |> # method 2
(\(foo) {
colN <- diff(foo@p)
cbind(foo@i + 1, rep(seq_along(colN), colN))
})(),
replications = 100
)
# test replications elapsed relative user.self sys.self user.child sys.child
# method 2 100 1.51 1.208 1.14 0.37 NA NA
# method 1 100 1.99 1.592 1.59 0.39 NA NA
# method 0 100 1.25 1.000 1.16 0.10 NA NA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment