@btime introduces a new scope?

I was trying to assess the big-O scaling (N vs N^2) for a couple of functions I had written. So I put @btime in a loop like this:
But apparently, k is not in the scope of @btime. This is probably obvious to someone that understands macros. I’m not there yet…Will someone help me understand this? Thanks.

for k ∈ [5,10,20]
    println(k)
    @btime v1(x[1],k);
    @btime v2(x[1],k);
end

this is the output:

5
ERROR: LoadError: UndefVarError: k not defined
Stacktrace:
 [1] ##core#678() at /Users/hart/.julia/packages/BenchmarkTools/eCEpo/src/execution.jl:371
...

OK, I found an answer to this elsewhere on discourse, so I’ll answer my own question and hope that it helps someone else:

Variables in the macro need to be global, not local, scope variables. $ can be used to interpolate to the value of the local variable in the @btime call.

Here’s the simple correction to my example:

for k ∈ [5,10,20]
    println(k)
    @btime v1(x[1],$k);
    @btime v2(x[1],$k);
end

and the output:

5
  107.532 ns (2 allocations: 144 bytes)
  63.393 ns (2 allocations: 144 bytes)
10
  187.909 ns (2 allocations: 176 bytes)
  80.880 ns (2 allocations: 176 bytes)
20
  358.810 ns (2 allocations: 256 bytes)
  115.605 ns (2 allocations: 256 bytes)

My “fast” version is sublinear in problem size.

1 Like