英文:
How to force the optimizer to keep some code in Julia?
问题
如何强制评估表达式,以防止它被优化掉?
在Rust中,我们可以使用一个名为black_box的内置函数,在Nim中可以使用used pragma,在C中可以创建一个volatile变量,在Zig中可以使用doNotOptimizeAway函数,在Haskell中可以使用evaluate来强制评估,等等。我该如何在Julia中实现这个?
另外,@elapsed实际上是否是测量经过时间的正确方式?我个人需要一个具有纳秒精度的单调定时器...
英文:
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...
答案1
得分: 5
如果你还没有看过的话,BenchmarkTools.jl 可能是你正在寻找的东西。
Base.donotdelete 会阻止死代码消除(但不会阻止 f() 被优化成一个常数,如果可能的话)。
f() = maximum(i^2 for i = 1:1000000000)
timeit1() = @elapsed f()
timeit2() = @elapsed Base.donotdelete(f())
timeit1() # 0.0
timeit2() # 大约 0.36
@elapsed 使用 Base.time_ns(),所以它具有纳秒级的精度。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论