问题描述
我正在尝试以正确的方式做某事。有时,正确的方法会花费很长时间,具体取决于输入。我真的不知道什么时候会先验。当正确的方法花费的时间太长时,我想去 hacking的方法。我如何让R监视执行一项特定任务的时间,如果超过阈值,又给它做其他事情?我以为这将是 try
家族的一部分,但我不太确定该如何称呼它或为Google付费。
I'm trying to do a thing "the right way". Sometimes "the right way" takes too long, depending on the inputs. I can't really know a priori when this will be. When "the right way" is taking too long, I want to go to "the hackish way". How do I make R monitor how long a particular task as taken, and give it something else to do if a threshold has passed? I'd imagine that this will be part of the try
family, but I'm not quite sure what to call it or google for.
下面的虚拟示例。当 slow.func
花费的时间太长时,我希望 interuptor
停止它并调用 fast。
Dummy example below. When
slow.func
takes too long, I want interuptor
to stop it and call fast.func
instead.
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
The R package
R.utils
has a function evalWithTimeout
that's pretty much exactly what you're describing. If you don't want to install a package, evalWithTimeout
relies on the less user friendly R base function 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中停止花费太长时间的功能并为其提供替代选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!