Thanks to you guys I have learned the method to kill the loop on the time limit.https://discourse.julialang.org/t/how-would-i-stop-a-while-loop-after-n-amount-of-time/84299/2 but I am still wondering if there is any method to skip to the next loop on time limit?
julia> time_start = time_ns()
@time while true
if time_ns() - time_start > 5e9
break
end
end
4.975468 seconds (23.11 M allocations: 352.
Does that work?
Here is a more elaborate example
julia> function f()
time_start = time_ns()
counter = 0
while true
if time_ns() - time_start > 5e9
break
end
counter += 1
end
return counter
end
f (generic function with 1 method)
julia> @time f()
5.000008 seconds
13306379
julia> @time f()
5.000006 seconds
13317871
Well…it is still the method to kill the loop.
My question is, for a for
loop, is there a way to conduct the continue
function on some time limit so that it can skip to the next loop.
time_ns() - time_start
may work! I would try that. thank you!
julia> function f()
f_start = time_ns()
for i in 1:10
iteration_start = time_ns()
println("Loop iteration $i at $((time_ns() - f_start)/1e9)")
t = @async sleep(i)
status = timedwait(3) do
istaskdone(t)
end
println("Iteration $i status: $status")
end
end
f (generic function with 1 method)
julia> f()
Loop iteration 1 at 1.928e-6
Iteration 1 status: ok
Loop iteration 2 at 1.054216979
Iteration 2 status: ok
Loop iteration 3 at 3.071932343
Iteration 3 status: ok
Loop iteration 4 at 6.14614505
Iteration 4 status: timed_out
Loop iteration 5 at 9.244185518
Iteration 5 status: timed_out
Loop iteration 6 at 12.322501454
Iteration 6 status: timed_out
Loop iteration 7 at 15.40138489
Iteration 7 status: timed_out
Loop iteration 8 at 18.473001556
Iteration 8 status: timed_out
Loop iteration 9 at 21.479161034
Iteration 9 status: timed_out
Loop iteration 10 at 24.544645199
Iteration 10 status: timed_out
4 Likes
I realized that if the loop needs to be terminated before a certain time, the function inside the loop is usually still running, which makes my request logically impossible. I will try to find another way to avoid this.
But still thank you for your code! Have learned much!