1
votes

I looking for a time-out function in Julia. My problem is as follows: I'm generating random strings that I want to test in my function. The problem is that some inputs cause an infinite running time. So I would like to set a max runtime for each run. My function only takes 1 argument: a String. Any help is welcome! TIA, Nico

1

1 Answers

3
votes

I'm not sure there is a good way without cooperation from the function you're calling (perhaps short of using multiple threads). You can use Timer:

julia> function repeat_forever(timer = Timer(1.0))
       while true
           isopen(timer) || break
           yield()
       end
       return "timer finished!"
   end
repeat_forever (generic function with 2 methods)

julia> @time repeat_forever(Timer(0.25))   # first call will be off due to compilation
  0.254629 seconds (484.42 k allocations: 7.454 MiB)
"timer finished!"

julia> @time repeat_forever(Timer(0.25))
  0.250661 seconds (484.81 k allocations: 7.398 MiB, 1.30% gc time)
"timer finished!"

julia> @time repeat_forever(Timer(1.25))
  1.250994 seconds (2.51 M allocations: 38.329 MiB, 0.27% gc time)
"timer finished!"

That yield call in the loop is necessary so that the timer task itself gets to run.