@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]
    @btime v1(x[1],k);
    @btime v2(x[1],k);

this is the output:

ERROR: LoadError: UndefVarError: k not defined
 [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]
    @btime v1(x[1],$k);
    @btime v2(x[1],$k);

and the output:

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

My “fast” version is sublinear in problem size.

1 Like