Retain computation results with @btime

I’m trying to time a function and keep its return value:
b = @btime y = foo(x)
but at the end y is not returned. How can get @btime to also return my result?

Use @belapsed instead.

1 Like

I’m not clear on why you need this. I use

bar = foo(spam);

when I want results and

@btime foo($spam);

when I want to see how fast my function is. These are different missions for me.

1 Like

@belapsed did not seem to work, @elapsed did. Moreover, @btime provides more info than just time and is supposed to be more accurate ?

What did not work? Can you show a reproducible example and tell us your expected behaviour?

1 Like

It sounds like you just want

y = @btime foo(x)

However, I don’t see how this is useful. If this is part of a computation where you use y later, you probably don’t want to run foo(x) multiple times (which is what @btime does).


This is what I meant. @belapsed cannot return the computation result as I needed.

What doesn’t work in the link I shared above?

julia> @eval BenchmarkTools macro btimed(args...)
           _, params = prunekwargs(args...)
           bench, trial, result = gensym(), gensym(), gensym()
           trialmin, trialallocs = gensym(), gensym()
           tune_phase = hasevals(params) ? :() : :($BenchmarkTools.tune!($bench))
           return esc(quote
               local $bench = $BenchmarkTools.@benchmarkable $(args...)
               local $trial, $result = $BenchmarkTools.run_result($bench)
               local $trialmin = $BenchmarkTools.minimum($trial)
               $result, $BenchmarkTools.time($trialmin)
@btimed (macro with 1 method)

julia> b, y = BenchmarkTools.@btimed sin(12.3)
(-0.26323179136580094, 1.371)

julia> b

julia> y

Isn’t this what you want?


Yes. I replied to the wrong post