Julia 1.x中类型不稳定函数带来性能后果的简单示例

Ant*_*llo 5 types julia type-stability

我发现所有用于说明Julia <0.6中类型不稳定性的性能瓶颈的示例在Julia> = 0.7中均不再有效,因为它们通常使用两种或几种可能的类型,但是现在编译器在处理Union{T1,T2,..}类型方面也很有效,因此与相应类型稳定版本的差异消失了。

您能否说明一个简单的类型不稳定函数的示例,当该类型变为类型稳定函数时,该函数仍具有较大的性能改进?

Bog*_*ski 6

通常,最明显的区别是全局变量引入类型不稳定性时。这是使用障碍函数消除类型不稳定性的示例:

x = 10

function f1()
    [i + x for i in 1:10^6]
end

function f2()
   h(x) = [i + x for i in 1:10^6]
   h(x)
end
Run Code Online (Sandbox Code Playgroud)

这是基准:

julia> using BenchmarkTools

julia> @benchmark f1()
BenchmarkTools.Trial:
  memory estimate:  38.13 MiB
  allocs estimate:  1998992
  --------------
  minimum time:     30.133 ms (3.66% GC)
  median time:      33.713 ms (3.39% GC)
  mean time:        35.206 ms (5.35% GC)
  maximum time:     100.575 ms (50.58% GC)
  --------------
  samples:          142
  evals/sample:     1

julia> @benchmark f2()
BenchmarkTools.Trial:
  memory estimate:  7.63 MiB
  allocs estimate:  2
  --------------
  minimum time:     2.325 ms (0.00% GC)
  median time:      3.286 ms (0.00% GC)
  mean time:        3.725 ms (20.26% GC)
  maximum time:     52.838 ms (93.68% GC)
  --------------
  samples:          1342
  evals/sample:     1
Run Code Online (Sandbox Code Playgroud)

性能损失的另一个常见情况是使用抽象eltype的容器(但我知道您没有将其归类为函数类型不稳定,因为它是数据类型不稳定)。