gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:45:10 25 4
gpt4 key购买 nike

我想运行一个执行时间不到一秒的函数。我想每秒循环运行一次。我不想在运行像 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com