Search code examples
loopsfor-loopjuliametaprogrammingbenchmarking

Separately time different lines in For Loop in Julia?


In Julia, I have a function that times each "kth" iteration of a for loop in the function using the @elapsed macro, and assigns such times to the variable t (and then vector time_vector). However, is there any way to write this function so that different lines within the for loop can be timed separately? I would like to time each line of the for loop, and insert the times into a two-dimensional array time_vector?

function timeloop(k)
    time_vector = zeros(k)
    for x = 1:k
         t = @elapsed 
             L₁=rand(10,k) #time this line with @elapsed?                
             L₂=rand(k,10) #time this line with @elapsed
             L₁*L₂ #time this line with #elapsed
         end
         time_vector[x] = t
     end 
     time_vector  
end 

Solution

  • You can return a vector of each single @elapsed like.

    function timeloop(k)
        time_vector = [zeros(3) for _ in 1:k]
        for x = 1:k
            t = [@elapsed L₁=rand(10,k)
                 @elapsed L₂=rand(k,10)
                 @elapsed L₁*L₂]
            time_vector[x] = t
        end 
        time_vector  
    end
    
    timeloop(5)
    #5-element Vector{Vector{Float64}}:
    # [1.604e-6, 3.63e-7, 1.1884e-5]
    # [5.56e-7, 5.61e-7, 1.193e-6]
    # [5.61e-7, 5.22e-7, 1.079e-6]
    # [2.471e-6, 5.39e-7, 1.086e-6]
    # [5.21e-7, 5.22e-7, 2.742e-6]