Search code examples
rtimeout

How to use withTimeout function to interrupt expression if it takes too long


I would like to terminate some code if a computation takes too long, i.e., it takes more than 2 seconds. I am trying to use the withTimeout function. Reading the example in the help, the following code is working and I get an error:

foo <- function() {
    print("Tic")
    for (kk in 1:100) {
    print(kk)
    Sys.sleep(0.1)
    }
print("Tac")
}

res <- withTimeout({foo()}, timeout = 2)

I tried to replicate this logic writing the following code, but it does not work, i.e., the computation ends even if the timeout has passed (on my laptop, it takes more or less 10 seconds).

res <- withTimeout({rnorm(100000000)}, timeout = 2)

Does anyone know why?


Solution

  • The rnorm example is a known "issue", which you can find on the R.utils GitHub site as a non-supported case.

    You can make this work by doing

    foo1 <- function(n = 1000000) { 
        ret <- rep(0, n); 
        for (kk in 1:n) ret[kk] <- rnorm(1); 
        ret; 
    }
    
    # The following will time out after 2s
    tryCatch( { res <- withTimeout( { foo1() },
        timeout = 2) },
        TimeoutException = function(ex) cat("Timed out\n"))
    #Timed out
    
    # Confirm that res is empty
    res
    #NULL