我正在尝试以“正确的方式”做某事。有时,“正确的方法”会花费很长时间,具体取决于输入。我真的不知道什么时候会先验。当“正确的方法”花费的时间太长时,我想去“hacking的方法”。我如何让R监视执行一项特定任务的时间,如果超过阈值,又给它做其他事情?我以为这将是try
家族的一部分,但我不太确定该如何称呼它或使用google。
下面的虚拟示例。当slow.func
花费的时间太长时,我希望interuptor
停止它并改为调用fast.func
。
slow.func <- function(x){
Sys.sleep(x)
print('good morning')
}
fast.func <- function(x){
Sys.sleep(x/10)
print('hit snooze')
}
interuptor = function(FUN,args, time.limit, ALTFUN){
# START MONITORING TIME HERE
do.call(FUN,args)
# IF FUN TAKES TOO LONG, STOP IT, CALL A
do.call(ALTFUN,args)
}
interuptor(slow.func, list(x = 2), time.limit = 1, fast.func)
最佳答案
R包R.utils
具有一个功能evalWithTimeout
,几乎与您所描述的完全一样。如果您不想安装软件包,则evalWithTimeout
依赖于对用户不太友好的R基本函数setTimeLimit
您的代码如下所示:
library(R.utils)
slow.func <- function(x){
Sys.sleep(10)
return(x^2)
}
fast.func <- function(x){
Sys.sleep(2)
return(x*x)
}
interruptor = function(FUN,args, time.limit, ALTFUN){
results <- NULL
results <- evalWithTimeout({FUN(args)},timeout=time.limit,onTimeout="warning")
if(results==NULL){
results <- ALTFUN(args)
}
return(results)
}
interruptor(slow.func,args=2,time.limit=3,fast.func)
关于r - 如何在R中停止花费太长时间的功能并为其提供替代选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346619/