LoginSignup
1
0

サイズの小さな線形代数計算を高速に行う

Last updated at Posted at 2023-07-10

結論

サイズの小さい、かつ固定長の線形代数の計算はStaticArrays.jlを使おう

実験

公式ドキュメントのPerformance Tipsには、計算結果をPre-allocateする工夫として、次の例が掲載されています。

function xinc(x)
    return [x, x+1, x+2]
end;

function loopinc()
    y = 0
    for i = 1:10^7
        ret = xinc(i)
        y += ret[2]
    end
    return y
end;

function xinc!(ret::AbstractVector{T}, x::T) where T
    ret[1] = x
    ret[2] = x+1
    ret[3] = x+2
    nothing
end;

function loopinc_prealloc()
    ret = Vector{Int}(undef, 3)
    y = 0
    for i = 1:10^7
        xinc!(ret, i)
        y += ret[2]
    end
    return y
end;

@time loopinc()
@time loopinc_prealloc()

結果は、手元の環境では

  0.323081 seconds (10.00 M allocations: 762.939 MiB, 14.33% gc time)
  0.035206 seconds (1 allocation: 80 bytes)

とメモリ消費量が減ったおかげでおよそ10倍計算時間が短くなりました。
しかし、StaticArrays.jlのMArrayを使うと

function loopinc_prealloc_Mvec()
    ret = @MVector zeros(Int, 3)
    y = 0
    for i = 1:10^7
        xinc!(ret, i)
        y += ret[2]
    end
    return y
end;

@time loopinc_prealloc_Mvec()
0.000001 seconds

なんとメモリ割り当てが0になり、計算時間がさらに約10000倍早くなりました。

まとめ

公式ドキュメントには最速のやり方を載せて欲しい

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0