I was converting some MATLAB code to Julia. In MATLAB to run a while loop for a set period is done using tic and toc functions. I was struggling with implementing the same thing in Julia.
My question in short is how to run a while loop for a specific period of time in Julia.
julia> function run(s)
t = time()
while time() < t + s
sleep(0.001)
end
end
run (generic function with 1 method)
julia> @time run(0.1)
0.101925 seconds (231 allocations: 6.766 KiB)
julia> @time run(0.5)
0.502150 seconds (1.14 k allocations: 34.453 KiB)
julia> @time run(1.2)
1.200282 seconds (2.75 k allocations: 83.469 KiB)
Probably in a real application you wouldn’t call sleep at all—your loop would be doing enough work that the overhead of occasional time calls would be negligible. (If not, you should just check the time every N-th iteration for a sufficiently large N.)