Allocations in function timing

Sorry for hijacking the topic, but as I was playing with the algorithms, I noticed that given this function:

julia> function main(n)
         r = 0
         for i = 1:n
           i -= 1
           r += 1
         end
         return r
       end
main (generic function with 1 method)

if we run

julia> @time main(10)
  0.000005 seconds (4 allocations: 160 bytes)
10

julia> @time main(100)
  0.000003 seconds (4 allocations: 160 bytes)
100

julia> @time main(1000)
  0.000002 seconds (5 allocations: 176 bytes)
1000

why does main(1000) end up with 5 allocations?

I looked at the code with all the @code_* macros and there was no difference between calling it with 100 and 1000.

Use BenchmarkTooks.jl for this kind of benchmarking.

1 Like

Thanks @dpsanders – I keep forgetting about BenchmarkTools !

Now consistently getting 0:

julia> @btime main(1000)
  2.324 ns (0 allocations: 0 bytes)
2 Likes