Search code examples
loopsfor-loopjuliaexpressionmetaprogramming

Time each iterations of For Loop in Julia?


Given a for loop, is there some macro/function that times each iteration of the loop, and returns this info as a tuple or array (or similar)? Would there be any way to assign such tuple or array to a variable (for example, I am not sure how to assign output of @time macro to a variable). I am aware of the @timed macro, but not sure how to extract the tuple that @timed gives/assign to variable. Below is an example of a for loop where each iteration might be timed?

 for x=1:10
     println("$x is my number.") 
 end

Solution

  • Like this?

    function timeloop(n)
        tvec = zeros(n)
        for x = 1:n
            t = @elapsed println("$x is my number.")
            tvec[x] = t
        end
        tvec
    end
    
    timeloop(9)
    1 is my number.
    2 is my number.
    3 is my number.
    4 is my number.
    5 is my number.
    6 is my number.
    7 is my number.
    8 is my number.
    9 is my number.
    
    9-element Vector{Float64}:
     0.0002649
     0.0001195
     0.0001018
     9.44e-5
     8.25e-5
     6.8e-5
     8.52e-5
     7.39e-5
     8.5e-5
    

    As per Julia help, @elapsed is a macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.

    For timing multi-line expressions/statements, use the t = @elapsed begin .. end form.