Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Last active November 26, 2021 19:14
Show Gist options
  • Save jmbarbone/835d7b13e53ac31a33cb551588f20744 to your computer and use it in GitHub Desktop.
Save jmbarbone/835d7b13e53ac31a33cb551588f20744 to your computer and use it in GitHub Desktop.
y <- runif(2000)
foo_loop <- function(y) {
m <- length(y)
res <- matrix(nrow = m, ncol = m)
for (i in 1:m) {
for (j in 1:m) {
res[i, j] <- all(y[i] <= y[j])
}
}
as.data.frame(res)
}
foo_vec <- function(y) {
as.data.frame(sapply(seq_along(y), \(i) y <= y[i]))
}
bench::mark(foo_loop(y), foo_vec(y))
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 x 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 foo_loop(y) 2.52s 2.52s 0.397 46.4MB 10.7
#> 2 foo_vec(y) 117.52ms 150.16ms 6.01 76.7MB 15.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment