我目前正面临一个我没有任何解释的问题。基本上在循环中,我将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(作为函数的参数),它将花费很长时间。此行为是否有任何逻辑原因?非常感谢!
正如@ThomasIscoding所说的,这必须与您在for loop
中的下一步工作有关,因为使用factor = 1
,factor = 1 / 2 * 2
或factor = 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创建