Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created October 4, 2014 03:34
Show Gist options
  • Save mrdwab/3c09f9419cd2b78eb19c to your computer and use it in GitHub Desktop.
Save mrdwab/3c09f9419cd2b78eb19c to your computer and use it in GitHub Desktop.
set.seed(1)
matches <- replicate(1000000, sample(20, sample(20), TRUE))
fun1 <- function() unlist(lapply(matches, sum))
fun2 <- function() sapply(matches, sum)
fun3 <- function() vapply(matches, sum, numeric(1L))
fun4 <- function() rapply(matches, sum)
library(microbenchmark)
microbenchmark(L = fun1(), S = fun2(), V = fun3(), R = fun4(), times = 10)
# Unit: seconds
# expr min lq mean median uq max neval
# L 2.380785 2.878558 3.133040 3.121355 3.546682 3.805213 10
# S 3.850449 4.199360 4.701659 4.645064 5.207675 5.784831 10
# V 2.200894 2.263745 2.481544 2.460322 2.511168 3.254304 10
# R 1.826686 1.975989 2.507679 2.638597 2.843158 2.988120 10
@josilber
Copy link

josilber commented Oct 4, 2014

lst <- lapply(1:100000, function(x) rnorm(sample(1:20)))
library(microbenchmark)
microbenchmark(sapply(matches, sum), vapply(matches, sum, numeric(1L)), unlist(lapply(matches, sum)), rapply(matches, sum))
# Unit: microseconds
#                               expr    min      lq  median
#               sapply(matches, sum) 17.036 21.4505 26.3890
#  vapply(matches, sum, numeric(1L))  4.752  6.6005  8.2630
#       unlist(lapply(matches, sum))  4.953  6.2420  6.9790
#               rapply(matches, sum) 20.731 22.9970 27.8265
#       uq     max neval
#  38.0180 108.439   100
#  11.6805  53.721   100
#  10.5695  20.266   100
#  39.7610 107.447   100

@mrdwab
Copy link
Author

mrdwab commented Oct 4, 2014

@josilber -- your system is faster than mine :-)

What OS? I wonder what else would contribute to such a difference....

Here's what I get for the same:

matches <- lapply(1:100000, function(x) rnorm(sample(1:20)))
library(microbenchmark)
microbenchmark(S = sapply(matches, sum), 
               V = vapply(matches, sum, numeric(1L)), 
               L = unlist(lapply(matches, sum)), 
               R = rapply(matches, sum), times = 20)
# Unit: milliseconds
#  expr      min       lq     mean   median       uq      max neval
#     S 325.6060 344.6757 393.8432 373.3158 431.6990 525.2846    20
#     V 174.7915 202.6937 225.3824 211.1571 241.4224 336.0206    20
#     L 206.3639 217.1771 257.6876 240.8964 269.2399 386.8028    20
#     R 141.8952 166.1317 187.5034 183.7426 201.6174 285.7413    20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment