How to force evaluation of an expression so it wouldn't get optimized out?
@elapsed f()
returns zero, as the result of pure function f
is unused.
In Rust we can use an intrinsic called black_box
, in Nim - used
pragma, in C we can make a volatile
variable, in Zig - doNotOptimizeAway
function, in Haskell we can use evaluate
to force the evaluation, and so on. How can i do this in Julia?
Also, is @elapsed
actually the proper way to measure elapsed time? I personally need a monotonic timer with nanosecond precision...
If you have not seen it already, BenchmarkTools.jl may be what you're looking for.
Base.donotdelete
will prevent dead code elimination (but won't stop f()
from being optimized into a constant, if that's possible).
f() = maximum(i^2 for i = 1:1000000000)
timeit1() = @elapsed f()
timeit2() = @elapsed Base.donotdelete(f())
timeit1() # 0.0
timeit2() # 0.36 ish
@elapsed
uses Base.time_ns()
, so it has nanosecond precision.