@btime eats my variables

Welcome!

The reason for your issue is that @btime is designed to operate at global scope, so any variables it references need to be globals. That doesn’t work in your case because x is a local, not a global variable. Fortunately, this is easy to work around: you can use $ to interpolate the value of x into the expression being benchmarked:

julia> function f(x)
         @btime $x^2
       end
f (generic function with 1 method)

julia> f(1)
  0.024 ns (0 allocations: 0 bytes)

Note also that this isn’t a general property of macros, but just a specific result of the fact that @btime and @benchmark are designed to treat all variables inside the expression you’re benchmarking as globals.

12 Likes