Created
October 30, 2024 14:20
-
-
Save thisisnic/6b76bf3678feb91fdfba84ea66f1f3a3 to your computer and use it in GitHub Desktop.
function for interrupting an R function execution if takes too long
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foo <- function() { | |
time_limit <- 3 | |
setTimeLimit(cpu = time_limit, elapsed = time_limit, transient = TRUE) | |
on.exit({ | |
setTimeLimit(cpu = Inf, elapsed = Inf, transient = FALSE) | |
}) | |
tryCatch({ | |
Sys.sleep(3.5) | |
print("done") | |
}, error = function(e) { | |
if (grepl("reached elapsed time limit|reached CPU time limit", e$message)) { | |
print("interrupted") | |
# we reached timeout, apply some alternative method or do something else | |
} else { | |
# error not related to timeout | |
stop(e) | |
} | |
}) | |
} | |
foo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment