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
| N = 10 input = lapply(1:N**2, function(x) matrix(rnorm(N**2), N)) a = do.call(function(...){ arglist = list(...) out = arglist[[1]] for (i in 2:length(arglist )) out = out + arglist[[i]] return(out) }, input) b = Reduce('+', input) for_sum = function(input){ out = input[[1]] for (i in 2:length(input)) out = out + input[[i]] return(out) } d = for_sum(input) all.equal(a, b) all.equal(a, d)
N = 200 K = 100 library(microbenchmark) microbenchmark(a = do.call(function(...){ arglist = list(...) out = arglist[[1]] for (i in 2:length(arglist )) out = out + arglist[[i]] return(out) }, lapply(1:K, function(x) matrix(rnorm(N**2), N))), b = Reduce('+', lapply(1:K, function(x) matrix(rnorm(N**2), N))), d = for_sum(lapply(1:K, function(x) matrix(rnorm(N**2), N))), times = 20L )
|