3

I'm trying to get a function to run for a specified amount of time, at the moment I'm trying to use the system.time function. I can't figure out how to define a new variable that takes on cumulative value the function running, then put it into a while loop.

timer<-(system.time(simulated_results<-replicate(n=1,simulation(J,10000,FALSE,0.1),simplify="vector"))[3])

print(timer)

while(cumsum(timer)<15){
    print(cumsum(timer)) 
    simulated_results<-replicate(n=10000,simulation(J,10000,FALSE,0.1),simplify="vector")
}

I would greatly appreciate any help!!!

juba
  • 47,631
  • 14
  • 113
  • 118
user124123
  • 1,642
  • 7
  • 30
  • 50
  • 2
    You might find `evalWithTimeout()` from the **R.utils** package helpful. [Here is one example](http://stackoverflow.com/questions/10952724/how-do-i-time-out-a-lapply-when-a-list-item-fails-or-takes-too-long/10953354#10953354) of how it can be used, in a slightly more complicated situation than you're asking about. – Josh O'Brien Jan 27 '13 at 20:59

2 Answers2

5

If you want to run some code for a specified number of seconds, you can try the following :

start <- as.numeric(Sys.time())
duration <- 5
results <- NULL
while(as.numeric(Sys.time())-start < duration) {
  results <- c(results, replicate(...))
}

Of course, you have to change the value of duration (in seconds), and replace replicate(...) with your code.

juba
  • 47,631
  • 14
  • 113
  • 118
  • I've just tried using the answer suggested by Juba so I've tried: start <- as.numeric(Sys.time()) duration <- 5 while(as.numeric(Sys.time())-start < duration) { simulated_results<-replicate(n=10000,simulation(J,10000,FALSE,0.1),s implify="vector") } but the functions not putting its results into the new vector "simulated_results" – user124123 Jan 27 '13 at 22:00
  • @user1987097 With your code, the `simulated_results` vector is replaced by the `replicate()` result after each iteration, so you have to append your new results to the previous ones each time (see edited answer). – juba Jan 27 '13 at 22:04
2

You can use a tryCatch approach and the package R.utils for this task. For example, consider the following code

fun_test = function(test_parameter){
  
  result <- 1+test_parameter #some execution
  return(result)
}
time = 10 #seconds
res <- NULL
tryCatch({
  res <- R.utils::withTimeout({
    check = fun_test(tsp)
  }, timeout = time)
}, TimeoutException = function(ex) {
  message("Timeout. Skipping.")
})

This program will run the function fun_test for 10 seconds (given by time. If the execution is successful in this time, the result is returned as res, else program is stopped. For more guidance, you can follow this URL Time out an R command via something like try()

Michael Roswell
  • 1,300
  • 12
  • 31
Sarwan Ali
  • 151
  • 1
  • 1
  • 11