@btime with local function --> not defined

dear J wizards—how do I use @btime inside a function with a passed argument?

julia> function testme( afun ); @btime begin afun(2) end end
testme (generic function with 1 method)

julia> testme( println )
ERROR: UndefVarError: afun not defined

@atime works, but afaik, it is not recommended for benchmarking.

1 Like

With interpolation, just like any other argument:

function testme(afun)
    @btime $afun(2) 
end
julia> f = x -> 2x
(::#36) (generic function with 1 method)

julia> testme(f)
  1.645 ns (0 allocations: 0 bytes)
4
4 Likes

Could someone explain what happens here ?

The problem is that macros are resolved at parse time so if you have

function testme(afun)
    @btime afun(2) 
end

then @btime can only see the name afun but not what it refers to.

1 Like