繁体   English   中英

for 循环中 R 舍入 difftime 的问题

[英]Issues with R rounding difftime in a for loop

运行以下命令来测试 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
}

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

逐行评估代码似乎有一些开销。 如果将它放入函数中,时间与没有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)

在此处输入图像描述

暂无
暂无

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

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