提问人:Dan Goldstein 提问时间:7/24/2009 最后编辑:TomasDan Goldstein 更新时间:11/22/2022 访问量:155023
如何在R中使执行暂停,休眠,等待X秒?
How to make execution pause, sleep, wait for X seconds in R?
问:
如何将 R 脚本暂停指定的秒数或毫秒数?在许多语言中,有一个函数,但引用一个数据集。而且不存在。sleep
?sleep
?pause
?wait
预期用途是用于自定时动画。所需的解决方案无需用户输入即可工作。
答:
189赞
Dirk Eddelbuettel
7/24/2009
#1
看。help(Sys.sleep)
例如,从?Sys.sleep
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
屈服
> testit(3.7)
user system elapsed
0.000 0.000 3.704
评论
1赞
Dan Goldstein
7/24/2009
下面是该页面中的示例代码。暂停 3.7 秒 testit <- function(x) { p1 <- proc.time() Sys.sleep(x) proc.time() - p1 # CPU 使用率应该可以忽略不计 } testit(3.7)
22赞
Dirk Eddelbuettel
7/24/2009
顺便说一句,help.search(“sleep”) 会引导你这样做。
0赞
Léo Léopold Hertz 준영
11/10/2016
为什么你不能做 ?Sys.sleep(10)
0赞
Dirk Eddelbuettel
11/10/2016
我想你误解了我的例子和说明,它也衡量并因此准确地证明了这一点,
19赞
rbtj
11/2/2017
#2
如果 CPU 使用率非常高,Sys.sleep() 将不起作用;与其他关键高优先级进程一样,正在运行(并行)。
这段代码对我有用。在这里,我以 1 秒的间隔打印 1 到 1000。
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
评论
1赞
Pake
4/4/2020
Sys.sleep() 函数在我的用例中不起作用,这是我能够管理产生必要延迟的唯一方法。
0赞
akbertram
12/21/2022
这就是所谓的“忙等待”,它将与其他线程和进程竞争 CPU 周期:en.wikipedia.org/wiki/Busy_waiting,您应该避免这种情况。Dirk 的以下答案是更好的解决方案。
4赞
polkas
11/22/2022
#3
TL;DR:全新稳定精准的睡眠功能sys_sleep
我们已经知道这可能无法按预期工作,例如当 CPU 使用率非常高时。
这就是为什么我决定准备一个由机械师驱动的高质量功能。Sys.sleep
microbenchmark::get_nanotime()
while/repeat
#' Alternative to Sys.sleep function
#' Expected to be more stable
#' @param val `numeric(1)` value to sleep.
#' @param unit `character(1)` the available units are nanoseconds ("ns"), microseconds ("us"), milliseconds ("ms"), seconds ("s").
#' @note dependency on `microbenchmark` package to reuse `microbenchmark::get_nanotime()`.
#' @examples
#' # sleep 1 second in different units
#' sys_sleep(1, "s")
#' sys_sleep(100, "ms")
#' sys_sleep(10**6, "us")
#' sys_sleep(10**9, "ns")
#'
#' sys_sleep(4.5)
#'
sys_sleep <- function(val, unit = c("s", "ms", "us", "ns")) {
start_time <- microbenchmark::get_nanotime()
stopifnot(is.numeric(val))
unit <- match.arg(unit, c("s", "ms", "us", "ns"))
val_ns <- switch (unit,
"s" = val * 10**9,
"ms" = val * 10**7,
"us" = val * 10**3,
"ns" = val
)
repeat {
current_time <- microbenchmark::get_nanotime()
diff_time <- current_time - start_time
if (diff_time > val_ns) break
}
}
system.time(sys_sleep(1, "s"))
#> user system elapsed
#> 1.015 0.014 1.030
system.time(sys_sleep(100, "ms"))
#> user system elapsed
#> 0.995 0.002 1.000
system.time(sys_sleep(10**6, "us"))
#> user system elapsed
#> 0.994 0.004 1.000
system.time(sys_sleep(10**9, "ns"))
#> user system elapsed
#> 0.992 0.006 1.000
system.time(sys_sleep(4.5))
#> user system elapsed
#> 4.490 0.008 4.500
创建于 2022-11-21 with reprex v2.0.2
评论