Simple Timeout of Function

I also want to mention another solution from later in the same thread. This defines a timeout function, which wraps an existing function and gives a different return value upon failure,

function timeout(f, arg, seconds, fail)
    tsk = @task f(arg)
    schedule(tsk)
    Timer(seconds) do timer
        istaskdone(tsk) || Base.throwto(tsk, InterruptException())
    end
    try
        fetch(tsk)
    catch _;
        fail
    end
end

This is more flexible when you want a function to have a time limit. For example, we can define a ‘time capped’ version of a function which returns a different value if the functio ntakes too long:

function rosenbrock2d(x)
    sleep(rand()*0.1)
    return (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
end

function rosenbrock2dtimelimit(x)
    return timeout(rosenbrock2d, x, 0.05, 1e99)
end

#We get roughly a 50/50 split between real values and timed out values.
for i = 1:10
    println(rosenbrock2dtimelimit([1,2]))
end

timeout() is a useful useful wrapper to objective functions in BlackBoxOptim or NLsolve.