evalWithTimeout

0th

Percentile

Evaluate an R expression and interrupts it if it takes too long

Evaluate an R expression and interrupts it if it takes too long.

Keywords
programming, IO
Usage
evalWithTimeout(..., envir=parent.frame(), timeout, cpu=timeout, elapsed=timeout,
  onTimeout=c("error", "warning", "silent"))
Arguments
...
The R expression to be evaluated as passed to eval().
envir
The environment in which the expression should be evaluated.
timeout, cpu, elapsed
A numeric specifying the maximum number of seconds the expression is allowed to run before being interrupted by the timeout. The cpu and elapsed arguments can be u
onTimeout
A character specifying what action to take if a timeout event occurs.
Details

This method utilizes setTimeLimit() by first setting the timeout limits, then evaluating the expression that may or may not timeout. The method is guaranteed to reset the timeout limits to be infitely long upon exiting, regardless whether it returns normally or preemptively due to a timeout or an error.

Value

  • Returns the results of the expression evaluated. If timed out, NULL is returned if onTimeout was "warning" or "silent". If "error" a TimeoutException is thrown.

Non-supported cases

It is not possible to interrupt/break out of a "readline" prompt (e.g. readline() and readLines()) using timeouts; the timeout exception will not be thrown until after the user completes the prompt (i.e. after pressing ENTER).

References

[1] R help thread 'Time out for a R Function' on 2010-12-06. http://www.mail-archive.com/r-help@r-project.org/msg119344.html

See Also

setTimeLimit()

Aliases
  • evalWithTimeout
Examples
# - - - - - - - - - - - - - - - - - - - - - - - - -
# Function that takes "a long" time to run
# - - - - - - - - - - - - - - - - - - - - - - - - -
foo <- function() {
  print("Tic");
  for (kk in 1:100) {
    print(kk);
    Sys.sleep(0.1);
  }
  print("Tac");
}


# - - - - - - - - - - - - - - - - - - - - - - - - -
# Evaluate code, if it takes too long, generate
# a timeout by throwing a TimeoutException.
# - - - - - - - - - - - - - - - - - - - - - - - - -
res <- NULL;
tryCatch({
  res <- evalWithTimeout({
    foo();
  }, timeout=1.08);
}, TimeoutException=function(ex) {
  cat("Timeout. Skipping.
");
})


# - - - - - - - - - - - - - - - - - - - - - - - - -
# Evaluate code, if it takes too long, generate
# a timeout returning NULL and generate a warning.
# - - - - - - - - - - - - - - - - - - - - - - - - -
res <- evalWithTimeout({
  foo();
}, timeout=1.08, onTimeout="warning");


# - - - - - - - - - - - - - - - - - - - - - - - - -
# Evaluate code, if it takes too long, generate
# a timeout, and return silently NULL.
# - - - - - - - - - - - - - - - - - - - - - - - - -
res <- evalWithTimeout({
  foo();
}, timeout=1.08, onTimeout="silent");
Documentation reproduced from package R.utils, version 1.28.4, License: LGPL (>= 2.1)

Community examples

Looks like there are no examples yet.