Time out an R command via something like try()

后端 未结 4 1232
清酒与你
清酒与你 2020-11-27 14:51

I\'m running a large number of iterations in parallel. Certain iterates take much (say 100x) longer than others. I want to time these out, but I\'d rather not have to dig in

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 15:19

    See this thread: http://r.789695.n4.nabble.com/Time-out-for-a-R-Function-td3075686.html

    and ?evalWithTimeout in the R.utils package.

    Here's an example:

    require(R.utils)
    
    ## function that can take a long time
    fn1 <- function(x)
    {
        for (i in 1:x^x)
        {
            rep(x, 1000)
        }
        return("finished")
    }
    
    ## test timeout
    evalWithTimeout(fn1(3), timeout = 1, onTimeout = "error") # should be fine
    evalWithTimeout(fn1(8), timeout = 1, onTimeout = "error") # should timeout
    

提交回复
热议问题