如果因数不是1,向量乘法会更快

问题描述 投票:0回答: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,则效果很好,一段时间后我得到了结果。但是,如果将factor设置为1(作为函数的参数),它将花费很长时间。此行为是否有任何逻辑原因?非常感谢!

r performance loops random time
1个回答
0
投票

正如@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 package(v0.3.0)在2020-04-16创建

© www.soinside.com 2019 - 2024. All rights reserved.