Different timing results when putting tic() toc() inside or outside a function

Here is a minimal working example to illustrate what I am trying to ask:

function test(n::Int)
tic()
i = 0
while (i <= n)
    A = randn(100,100)
    B = randn(100,100)
    C = A*B
    i+=1
end
toc()
end

test(100)

I always time my functions by putting @time in front of the function call (like @time test(100)). However, I realized that if I put tic() and toc() inside the function definition, then the timing result could be quite different.

For the example above, I get elapsed time: 0.033487528 seconds. However, if I remove the tic() and toc() and use

tic()
test(100)
toc()

then I get elapsed time: 0.047568188 seconds. (In both case, the code is run at least twice to avoid the compilation time.)

I don’t really understand what influences the gap between the two ways of timing. I am asking this because in my actual project, I encounter a timing difference of about 0.66 second and 0.015 second, which is quite significant! What are the common reasons for making this gap large? Thanks!

Is this related to:

?


Don’t (usually) use tic and toc; do use BenchmarkTooks.jl for micro-benchmarking, or @time if the function runs for long enough (seconds).

2 Likes