AnyMath 文档

长凳,长凳

该页面正在翻译中。

BenchmarkTools通过提供一个框架*编写和运行基准测试组*以及*比较基准测试结果*,使*Julia代码的性能跟踪变得容易*。

此包用于编写和运行在https://github.com/JuliaCI/BaseBenchmarks.jl[BaseBenchmarks.jl]。

用于Julia语言的自动性能测试的CI基础结构不在此包中,但可以在https://github.com/JuliaCI/Nanosoldier.jl[Nanosoldier.jl]。

快速启动

BenchmarkTools提供的主要宏是 @基准:

julia> using BenchmarkTools

# The `setup` expression is run once per sample, and is not included in the
# timing results. Note that each sample can require multiple evaluations
# benchmark kernel evaluations. See the BenchmarkTools manual for details.
julia> @benchmark sort(data) setup=(data=rand(10))
BenchmarkTools.Trial:
 10000 samples with 968 evaulations took a median time of 90.902 ns (0.00% GC)
 Time  (mean ± σ):   94.936 ns ±  47.797 ns  (GC: 2.78% ±  5.03%)
 Range (min … max):  77.655 ns … 954.823 ns  (GC: 0.00% … 87.94%)

          ▁▃▅▆▇█▇▆▅▂▁
  ▂▂▃▃▄▅▆▇███████████▇▆▄▄▃▃▂▂▂▂▂▂▂▂▂▂▂▁▂▁▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂
  77.7 ns         Histogram: frequency by time           137 ns

 Memory estimate: 160 bytes, allocs estimate: 1.

对于快速理智检查,可以使用https://juliaci.github.io/BenchmarkTools.jl/stable/manual/#Benchmarking-basics[脧锚脧赂`@btime` 宏],这是一个方便的包装 @基准 其输出类似于朱莉娅的内置https://docs.julialang.org/en/v1/base/base/#Base.@time[脧锚脧赂`@时间` 宏]:

julia> @btime sin(x) setup=(x=rand())
  4.361 ns (0 allocations: 0 bytes)
0.49587200950472454

如果您对分析快速运行的命令感兴趣,可以使用 @bprofile sin(x)setup=(x=rand()) 然后你最喜欢的工具来显示结果(个人资料。印刷业 或图形查看器)。

如果要基准测试的表达式依赖于外部变量,则应使用https://juliaci.github.io/BenchmarkTools.jl/stable/manual/#Interpolating-values-into-benchmark-expressions[$ 将它们"插值"到基准表达式中,以https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-global-variables[避免使用全局变量进行基准测试的问题]。 本质上,任何插值变量 $x 或表达 $(...) 在基准测试开始之前是"预先计算的":

julia> A = rand(3,3);

julia> @btime inv($A);            # we interpolate the global variable A with $A
  1.191 μs (10 allocations: 2.31 KiB)

julia> @btime inv($(rand(3,3)));  # interpolation: the rand(3,3) call occurs before benchmarking
  1.192 μs (10 allocations: 2.31 KiB)

julia> @btime inv(rand(3,3));     # the rand(3,3) call is included in the benchmark time
  1.295 μs (11 allocations: 2.47 KiB)

有时,将变量插值到非常简单的表达式中会给编译器提供比您预期的更多的信息,导致它通过将计算从基准代码中提升出来来"欺骗"基准

julia> a = 1; b = 2
2

julia> @btime $a + $b
  0.024 ns (0 allocations: 0 bytes)
3

根据经验,如果基准报告执行时间不到一纳秒,则可能会发生这种提升。 您可以通过引用和解引用插值变量来避免这种情况

julia> @btime $(Ref(a))[] + $(Ref(b))[]
  1.277 ns (0 allocations: 0 bytes)
3

如所述https://juliaci.github.io/BenchmarkTools.jl/stable/reference/[手动],BenchmarkTools软件包支持许多其他功能,既可用于额外的输出,也可用于对基准测试过程进行更细粒度的控制。