具有步骤执行时间限制的For循环
我想对for循环的每个步骤的执行时间进行限制。简单地说,如果该步骤没有在10秒内完成,那么请转到具有步骤执行时间限制的For循环,r,R,我想对for循环的每个步骤的执行时间进行限制。简单地说,如果该步骤没有在10秒内完成,那么请转到next 更具体地说,这里有一些代码 myComplicatedFunction <- function(obj, ...) { <some code here> } x # something to process x_result <- vector(mode = "list", length = length(x)) for (i in seq_along(x)) {
next
更具体地说,这里有一些代码
myComplicatedFunction <- function(obj, ...) { <some code here> }
x # something to process
x_result <- vector(mode = "list", length = length(x))
for (i in seq_along(x)) {
x_result[[i]] <-
processNotMoreThanXSeconds(
givenTime = 10,
myComplicatedFunction(x[i]),
didNotComplete = function() "Time's up!"
)
}
myComplementFunction您可以使用setTimeLimit
(它是base R的一部分):
如果达到时间限制,函数将返回一个错误(如运行上述操作,处理需要7秒,但限制为5秒)。您可以使用try
来处理错误并继续循环:
myerror <- try({
setTimeLimit({
Sys.sleep(7)
}, elapsed = 5)
}, silent = TRUE)
class(myerror)
#[1] "try-error"
myerror <- try({
setTimeLimit({
Sys.sleep(7)
}, elapsed = 5)
}, silent = TRUE)
class(myerror)
#[1] "try-error"
if (class(myerror) == 'try-error') {
next
}