# Measuring time of only a part of a for-loop

Hi,

is there a way to the following:

for i in 1:100
if i == 2
@time begin
elseif i == 88
end
end
end


Obviously this code does not work, but I think it makes it clear what I want to achieve: measuring the time that is needed in the loop for 2 \leq i \leq 88. Is this somehow possible? Thanks in advance!

Best regards,
Handam

I think GitHub - KristofferC/TimerOutputs.jl: Formatted output of timed sections in Julia should do what you’re looking for.

1 Like

Thanks for the quick answer!

I am still not sure what the best way is to solve my problem with the TimerOutputs package. I guess one solution would be

function instructions()
#Some instructions
end

const to = TimerOutput()
for i in 1:100
if i>=2 && i<= 88
@timeit to "part_of_loop" instructions()
else
instructions()
end
end


but that feels a little bit odd.
Other things I tried, which didn’t work though, were for example:

const to = TimerOutput()
disable_timer!(to)
@timeit to "part_of_loop" begin
for i in 1:100
if i == 2
enable_timer!(to)
elseif i == 88
disable_timer!(to)
end
#Some instructions
end
end


Any better solution than my first example?

One ugly way, but very effective, way is to triplicate your loop: copy the loop body three times and change the respective intervals to 1:1, 2:88, and 89:100; then wrap only the second loop with timing.

You could get your second example to work with:

const to = TimerOutput()
disable_timer!(to)
for i in 1:100
if i == 2
enable_timer!(to)
elseif i == 88
disable_timer!(to)
end
@timeit to "part_of_loop" begin
#instructions
end
end
end