Time out an R command via something like try()

后端 未结 4 1227
清酒与你
清酒与你 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:10

    I like R.utils::withTimeout(), but I also aspire to avoid package dependencies if I can. Here is a solution in base R. Please note the on.exit() call. It makes sure to remove the time limit even if your expression throws an error.

    with_timeout <- function(expr, cpu, elapsed){
      expr <- substitute(expr)
      envir <- parent.frame()
      setTimeLimit(cpu = cpu, elapsed = elapsed, transient = TRUE)
      on.exit(setTimeLimit(cpu = Inf, elapsed = Inf, transient = FALSE))
      eval(expr, envir = envir)
    }
    

提交回复
热议问题