gpt4 book ai didi

r - setTimeLimit 在函数完成后仍然存在

转载 作者:行者123 更新时间:2023-12-01 01:15:06 25 4
gpt4 key购买 nike

使用简单的测试功能

timefoo<-function(x,trans=TRUE){
setTimeLimit(elapse=4, transient=trans)
warning('starting...')
Sys.sleep(x)
warning('woke up')
return(x)
}

当我调用 timefoo(5) 时,该函数会正确终止, 但:
 timefoo(3)
[1] 3
Warning messages:
1: In timefoo(3) : starting...
2: In timefoo(3) : woke up
Error: reached elapsed time limit

有人能解释一下到底发生了什么吗?就好像 setTimeLimit继续追 timefoo已完成并退出。设置 transient=FALSE更糟糕的是,它会为我的控制台命令设置超时,并在每个命令(加上 4 秒)后给我错误消息。

编辑:为了回应 Gavin 的问题,这里有两个电话的序列
Rgames> timefoo(5)
Error in Sys.sleep(x) : reached elapsed time limit
In addition: Warning message:
In timefoo(5) : starting...
Rgames> timefoo(3)
[1] 3
Warning messages:
1: In timefoo(3) : starting...
2: In timefoo(3) : woke up
Error: reached elapsed time limit

我在命令之间手动等待了 10 秒,因此毫无疑问,最终的错误消息是由 timefoo(3) 引起的。称呼。是否有任何我可能弄脏的 R_ENVIRON 变量导致了这种行为?到目前为止,我仅在 Windows7、R64 上对此进行了测试。

最佳答案

我收到相同的错误消息(在 Win 7 下运行 R-2.16 devel)。

帮助页面 ?setTimeLimit状态:

‘setTimeLimit’ sets limits which apply to each top-level computation, that is a command line (including any continuation lines) entered at the console or from a file.



所以它并不是真正设计为从函数内部运行。如果您想这样做,请尝试以下替代方法:
timed_computation <- function(expr, time_limit = 1)
{
setTimeLimit(elapsed = time_limit, transient = TRUE)
ans <- expr
setTimeLimit(elapsed = Inf, transient = TRUE)
ans
}

timed_computation(1 + 1) #should return 2
timed_computation(Sys.sleep(2)) #should throw an error

关于r - setTimeLimit 在函数完成后仍然存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514899/

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