如何强制优化器在Julia中保留一些代码?

huangapple go评论74阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月18日 22:24:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定