首页 > 解决方案 > 如果因子不是 1,向量乘法更快

问题描述

我目前面临一个我没有任何解释的问题。基本上在一个循环中,我将 100 个随机点的向量与一个数字相乘。像这样:

for(i in 1:10000) {
  xs <- runif(100,0,1)
  ys <- runif(100,0,1)
  data <- factor*cbind(xs,ys)
  #do something with the data
}

例如,如果我设置factor <- 3它工作正常,一段时间后我就有了我的结果。但是如果因子设置为 1(作为函数的参数),它需要永远。这种行为有什么合乎逻辑的原因吗?非常感谢!

标签: rperformanceloopsrandomtime

解决方案


正如@ThomasIscoding 所说,这一定是关于你接下来要做什么的事情,因为用,或for loop调用那段代码没有显着区别:factor = 1factor = 1 / 2 * 2factor = 3

library(microbenchmark)

fn <- function(factor = 1) {
  for (i in 1:10000) {
    xs <- runif(100, 0, 1)
    ys <- runif(100, 0, 1)
    data <- factor * cbind(xs, ys)
    #do something with the data
  }

  return(data)
}

microbenchmark(fn(1),
               fn(1 / 2 * 2),
               fn(3),
               times = 10L)
#> Unit: milliseconds
#>         expr      min       lq     mean   median       uq      max neval cld
#>        fn(1) 102.8349 108.2655 109.9209 108.6099 111.8287 122.4011    10   a
#>  fn(1/2 * 2) 101.8430 103.7025 112.1260 107.5010 111.9726 150.9856    10   a
#>        fn(3) 102.3946 105.0698 109.6703 107.7922 114.4457 119.2038    10   a

reprex 包(v0.3.0)于 2020-04-16 创建


推荐阅读