r - 我如何每秒运行一个函数

标签 r

我想运行一个执行时间不到一秒的函数。我想每秒循环运行一次。我不想在运行像 Sys.sleep 这样的函数之间等待一秒钟会做。

while(TRUE){
  # my function that takes less than a second to run
  Sys.sleep(runif(1, min=0, max=.8))  

  # wait for the remaining time until the next execution...
  # something here
}

我可以录制 starttime <- Sys.time()并在循环中的每次迭代中进行比较,就像这样......
starttime <- Sys.time()
while(TRUE){
  if(abs(as.numeric(Sys.time() - starttime) %% 1) < .001){
    # my function that takes less than a second to run
    Sys.sleep(runif(1, min=0, max=.8))  
    print(paste("it ran", Sys.time()))
  }
}

但我的功能似乎从未被执行过。

我知道 python 有一个包来做这种事情。 R 是否也有一个我不知道的?谢谢。

最佳答案

您可以通过 system.time 跟踪时间

while(TRUE)
{
    s = system.time(Sys.sleep(runif(1, min = 0, max = 0.8)))
    Sys.sleep(1 - s[3]) #basically sleep for whatever is left of the second
}

您也可以使用 proc.time直接(哪个 system.time 调用),由于某些原因,这对我来说得到了更好的结果:
> system.time(
  for(i in 1:10)
  {
    p1 = proc.time()
    Sys.sleep(runif(1, min = 0, max = 0.8))
    p2 = proc.time() - p1
    Sys.sleep(1 - p2[3]) #basically sleep for whatever is left of the second
  })
   user  system elapsed 
   0.00    0.00   10.02

关于r - 我如何每秒运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36086599/

相关文章:

r - 计算行意味着仅针对在 R 中具有多个数据点的行

r - dplyr 根据订单条件和 if 语句进行汇总

R ggplot 将 xtick 从完整日期更改为星期几

r - 创建格状(多面)薄板样条响应曲面

r - 如何随机化列顺序的子集

r - 如何使用 sliderInput 在 R Shiny 中输入超过 2 个值

r - 将 vertex.label 放置在 igraph 中的圆形布局之外

r - 更改我的 ggplot 树状图中的字体

r - 查找两列中的重复项

r - 提取包含另一列的每个唯一值的第一个值的所有行