【问题标题】:Issues with R rounding difftime in a for loop在 for 循环中 R 舍入 difftime 的问题
【发布时间】:2021-10-10 04:42:00
【问题描述】:

运行以下命令来测试 runif() 的运行速度:

start_time <- Sys.time()
  runif(1)
  end_time <- Sys.time()
  run_times= as.numeric(as.difftime(end_time - start_time, units ="secs"))

run_times "0.3906578" 只需要几分之一秒

但是在 for 循环中运行它每次运行都会踢出 0:

nvec=c(1,100)
uni_time_vec=numeric(length(nvec))
for (i in 1:length(nvec)) {
  start_time <- Sys.time()
  runif(1)                   #hardcoded for testing
  end_time <- Sys.time()
  run_times= as.numeric(as.difftime(end_time - start_time, units ="secs"))
  uni_time_vec[i] = run_times
}

发生了什么,我该如何解决?

【问题讨论】:

  • 对我来说很好。我可以在控制台中看到uni_time_vec.Run options(digits = 15) 中非常小的值,然后重试。
  • 嘿 Ronak,所以运行那条线并使用它更有帮助,我可以得到非常小的值而不是 0。但它只有在我创建错误时才有效(奇怪)。在 for 循环中,我不小心遗漏了一个右括号“for (i in 1:length(nvec) {”,它返回并出现意外错误,但完成了。当我将括号添加回去时,它会返回仅返回 0。

标签: r output difftime


【解决方案1】:

按行评估代码似乎有一些开销。如果将其放入函数中,则时间与没有 for 循环优势的版本非常相似,这是我们所期望的。

f1 <- function() {
  stm <- Sys.time()
  runif(1)
  Sys.time() - stm
}

f2 <- function() {
  r <- NULL
  for (i in 1) {
    stm <- Sys.time()
    runif(1)                   #hardcoded for testing
    r[i] <- Sys.time() - stm
  }
  r
}

set.seed(42)
R <- 1e5L
t1 <- replicate(R, f1())
t2 <- replicate(R, f2())
lapply(list(t1=t1, t2=t2), summary)
# $t1
# Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
# 5.72e-06 6.44e-06 6.68e-06 7.37e-06 6.68e-06 4.09e-02 
# 
# $t2
# Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
# 5.960e-06 6.680e-06 6.680e-06 7.580e-06 6.910e-06 3.955e-02 

可视化

u <- range(c(t1, t2))
d1 <- density(r1, from=u[1], to=u[2]); d2 <- density(r2, from=u[1], to=u[2])
plot(d1, log='x', ylim=c(0, max(c(d1$y, d2$y))), col=2, xlab='Sys.time', main='')
lines(d2, col=3)
legend('topright', legend=c('alone', 'in `for` loop'), lty=1, col=2:3)

【讨论】:

    猜你喜欢
    • 2011-06-10
    • 2020-02-03
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2015-01-19
    • 2015-01-19
    • 2011-04-26
    相关资源
    最近更新 更多