I would like to create a function to time test various operations, but it seems that invoking @btime
(from BenchmarkTools
) doesn’t work in this situation. Is there a way to use @btime
inside a function. (Note: @time
works.)
For example:
using BenchmarkTools
function mult_time_1(n=100)
A = rand(n,n)
@time A^2
nothing
end
function mult_time_2(n=100)
A = rand(n,n)
@btime A^2
nothing
end
In this example, mult_time_1
works fine, but mult_time_2
gives the following error:
julia> mult_time_2()
ERROR: UndefVarError: `A` not defined
Stacktrace:
[1] var"##core#262"()
@ Main ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:547
[2] var"##sample#263"(::Tuple{}, __params::BenchmarkTools.Parameters)
@ Main ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:556
[3] _run(b::BenchmarkTools.Benchmark, p::BenchmarkTools.Parameters; verbose::Bool, pad::String, kwargs::@Kwargs{…})
@ BenchmarkTools ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:109
[4] #invokelatest#2
@ ./essentials.jl:889 [inlined]
[5] invokelatest
@ ./essentials.jl:884 [inlined]
[6] #run_result#45
@ ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:41 [inlined]
[7] run_result
@ ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:40 [inlined]
[8] run(b::BenchmarkTools.Benchmark, p::BenchmarkTools.Parameters; progressid::Nothing, nleaves::Float64, ndone::Float64, kwargs::@Kwargs{…})
@ BenchmarkTools ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:134
[9] run (repeats 2 times)
@ BenchmarkTools ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:126 [inlined]
[10] #warmup#54
@ BenchmarkTools ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:189 [inlined]
[11] warmup(item::BenchmarkTools.Benchmark)
@ BenchmarkTools ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:188
[12] macro expansion
@ ~/.julia/packages/BenchmarkTools/QAv7m/src/execution.jl:652 [inlined]
[13] mult_time_2(n::Int64)
@ Main ~/.julia/dev/MiniMods/test/test_test.jl:12
[14] mult_time_2()
@ Main ~/.julia/dev/MiniMods/test/test_test.jl:11
[15] top-level scope
@ REPL[11]:1