如何让R执行暂停,休眠,等待X秒?

问题描述 投票:105回答:2

如何暂停R脚本达指定的秒数或毫秒数?在许多语言中,有一个sleep函数,但?sleep引用了一个数据集。并且?pause?wait不存在。

预期目的是用于自定时动画。所需的解决方案无需用户输入即可运行。

r animation statistics
2个回答
124
投票

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 

5
投票

如果CPU使用率非常高,则Sys.sleep()将不起作用;正如在其他关键的高优先级进程中运行(并行)。

这段代码对我有用。这里我以2.5秒的间隔打印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
}
© www.soinside.com 2019 - 2024. All rights reserved.