简体   繁体   English

哪个是累积向量的更有效方法?

[英]Which is the more efficient way to accumulate a vector?

Which of the following is more efficient in terms of time to completion? 就完成时间而言,以下哪项更有效?

one.way = function(n) { if (n) c(n, one.way(n-1)) }
two.way = function(n) { if (n) c(two.way(n-1), n) }

The emphasis here is on which order to combine a singleton vector with another vector whose length is likely greater than one. 这里的重点是将单例向量与长度可能大于一个的另一个向量组合的顺序。

How would your answer change if you need to include the time to reverse the vector after constructing it with one of the above functions? 如果使用上述函数之一构建向量后需要包括反向向量的时间,答案将如何变化? It may or may not be known at the time of combination in which order the combined objects are going to be needed. 在组合时可能需要或可能不知道组合对象的顺序。

To answer your question, they're about equal 要回答您的问题,它们大致相等

Use microbenchmark to test the performance of two fast functions 使用微microbenchmark测试两个快速功能的性能

one.way = function(n) { c(n, 1) }
two.way = function(n) { c(1, n) }

n <- 2:100

library(microbenchmark)
microbenchmark(one.way(n), two.way(n), times=1e5)

#       expr   min    lq     mean median    uq      max neval
# one.way(n) 1.399 1.866 2.009775  1.867 1.867 2817.733 1e+05
# two.way(n) 1.399 1.866 2.086267  1.867 1.867 3394.808 1e+05

Notice the lower-quartile, median, and upper-quartile are all the same. 注意下四分位数,中位数和上四分位数都相同。 The means are slightly different but it's not significant. 手段略有不同,但意义不大。 See below 见下文

myfun <- function(n) {
              temp <- microbenchmark(one.way(n), two.way(n), times=1e5)
              df <- data.frame(one.way = mean(temp$time[temp$expr=="one.way(n)"]),
                           two.way = mean(temp$time[temp$expr=="two.way(n)"]))
              return(df)
     }

library(purrr)
test <- map_df(1:100, ~myfun(n))

t.test(test$one.way, test$two.way)

# data:  test$one.way and test$two.way
# t = -1.6506, df = 182.72, p-value = 0.1005
# alternative hypothesis: true difference in means is not equal to 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM