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.
Any help would be appreciated. Thanks.
julia> function run(s)
t = time()
while time() < t + s
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)
this is probably close to your tic toc in MATLAB
That is exactly what I was looking for! Thanks alot.
wondering why allocations depend on s…
You can use sleep_ms(1) from the package Timers, much more accurate and non-allocating…
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.)