只要经过的时间超过 1 分钟,默认单位就会从秒更改为分钟。所以你想控制单位:
while (difftime(Sys.time(), tm, units = "secs")[[1]] < period)
来自?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"’.
或者使用proc.time,它以秒为单位测量自您开始 R 会话以来的各种时间(“用户”、“系统”、“经过”)。我们想要“经过”的时间,即挂钟时间,所以我们检索proc.time() 的第三个值。
period <- 10
tm <- proc.time()[[3]]
while (proc.time()[[3]] - tm < period) print(proc.time())
如果您对[[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
“自动”单位非常聪明。如果sleep_time_in_secs = 3605(超过一个小时),默认单位将更改为“小时”。
使用Sys.time 时请注意时间单位,否则您可能会在基准测试中被愚弄。这是一个完美的例子:Unexpected results in benchmark of 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
“用户”时间和“系统”时间都是0,因为CPU和系统内核都是空闲的。