我可以使用以下代码运行一段代码5或10秒:
period <- 10 ## minimum time (in seconds) that the loop should run for
tm <- Sys.time() ## starting data & time
while(Sys.time() - tm < period) print(Sys.time())
Run Code Online (Sandbox Code Playgroud)
代码运行良好5或10秒.但是当我将周期值替换为60以使其运行一分钟时,代码永远不会停止.怎么了?
李哲源*_*李哲源 18
一旦经过的时间超过1分钟,默认单位就会从几秒钟变为几分钟.所以你想控制单位:
while (difftime(Sys.time(), tm, units = "secs")[[1]] < period)
Run Code Online (Sandbox Code Playgroud)
从 ?difftime
If ‘units = "auto"’, a suitable set of units is chosen, the
largest possible (excluding ‘"weeks"’) in which all the absolute
differences are greater than one.
Subtraction of date-time objects gives an object of this class, by
calling ‘difftime’ with ‘units = "auto"’.
Run Code Online (Sandbox Code Playgroud)
或者使用proc.time,它可以在几秒钟内开始您的R会话,从而测量各种时间("用户","系统","已过去").我们想要"过去"的时间,即挂钟时间,所以我们检索第3个值proc.time().
period <- 10
tm <- proc.time()[[3]]
while (proc.time()[[3]] - tm < period) print(proc.time())
Run Code Online (Sandbox Code Playgroud)
如果您对使用[[1]]和感到困惑[[3]],请咨询:
让我添加一些用户友好的可重现的例子.print在循环内部的原始代码非常烦人,因为它会在屏幕上打印数千行.我会用Sys.sleep.
test.Sys.time <- function(sleep_time_in_secs) {
t1 <- Sys.time()
Sys.sleep(sleep_time_in_secs)
t2 <- Sys.time()
## units = "auto"
print(t2 - t1)
## units = "secs"
print(difftime(t2, t1, units = "secs"))
## use '[[1]]' for clean output
print(difftime(t2, t1, units = "secs")[[1]])
}
test.Sys.time(5)
#Time difference of 5.005247 secs
#Time difference of 5.005247 secs
#[1] 5.005247
test.Sys.time(65)
#Time difference of 1.084357 mins
#Time difference of 65.06141 secs
#[1] 65.06141
Run Code Online (Sandbox Code Playgroud)
"自动"单位非常聪明.如果sleep_time_in_secs = 3605(超过一小时),默认单位将更改为"小时".
使用时要小心时间单位Sys.time,否则你可能会在基准测试中被愚弄.这是一个完美的例子:read.csv/fread基准测试的意外结果.我用一个现已删除的评论回答了它:
你有时间单位的问题.我看到它
fread快了20多倍.如果fread需要4秒钟来读取文件,则read.csv需要80秒= 1.33分钟.忽略单位,read.csv"更快".
现在让我们来测试吧proc.time.
test.proc.time <- function(sleep_time_in_secs) {
t1 <- proc.time()
Sys.sleep(sleep_time_in_secs)
t2 <- proc.time()
## print user, system, elapsed time
print(t2 - t1)
## use '[[3]]' for clean output of elapsed time
print((t2 - t1)[[3]])
}
test.proc.time(5)
# user system elapsed
# 0.000 0.000 5.005
#[1] 5.005
test.proc.time(65)
# user system elapsed
# 0.000 0.000 65.057
#[1] 65.057
Run Code Online (Sandbox Code Playgroud)
"用户"时间和"系统"时间为0,因为CPU和系统内核都处于空闲状态.