Reputation: 2584
I want to make a restriction on execution time for every step of the for loop. Simply, if the step didn't complete in 10 seconds, then go next
.
To be more specific, here is some code.
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!"
)
}
My question is, how to declare such function processNotMoreThanXSeconds
?
Upvotes: 3
Views: 91
Reputation: 37879
You can use setTimeLimit
(it is part of base R):
setTimeLimit({
Sys.sleep(7)
}, elapsed = 5)
If the time limit is reached the function will return an error (like if you run the above, processing takes 7 secs but the limit is 5). You can tie this up with try
in order to handle the error and continue the loop:
myerror <- try({
setTimeLimit({
Sys.sleep(7)
}, elapsed = 5)
}, silent = TRUE)
class(myerror)
#[1] "try-error"
Then use an if-else statement to check if there was an error and continue. Something like:
if (class(myerror) == 'try-error') {
next
}
Upvotes: 6