[英]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.