@btime's wrong output

What’s wrong with the following code? (Julia 1.0.4)

julia> using BenchmarkTools

julia> a = [1,2,3,4,5]
5-element Array{Int64,1}:
1
2
3
4
5

julia> @btime $a .= $a.^2
9.499 ns (0 allocations: 0 bytes)
5-element Array{Int64,1}:
1
0
1
0
1

It evaluates your expression many times. That is the result of evaluating that expression a lot of times.

3 Likes

For some more details, this happens because of lots of int overflow.

2 Likes

This is quite beautiful, actually. It converged to the two fixed points :slight_smile:.

5 Likes

Try with Float64 and the ideas of @Oscar_Smith and @StefanKarpinski become clearer.

julia> a = [1.0,2,3,4,5]
5-element Array{Float64,1}:
 1.0
 2.0
 3.0
 4.0
 5.0

julia> @btime $a .= $a.^2
  8.724 ns (0 allocations: 0 bytes)
5-element Array{Float64,1}:
   1.0
 Inf
 Inf
 Inf
 Inf

But when you remove the in-place dot, you get what you expected:

julia> a = [1,2,3,4,5]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> @btime $a = $a.^2
  245.757 ns (2 allocations: 160 bytes)
5-element Array{Int64,1}:
  1
  4
  9
 16
 25
2 Likes

Thank you all. Enjoyed your interesting answers :slight_smile: