gpt4 book ai didi

optimization - 使用 StaticArrays 有效地填充矩阵中的 block

转载 作者:行者123 更新时间:2023-12-04 15:09:08 24 4
gpt4 key购买 nike

使用静态数组时,我注意到根据您转换/创建静态矩阵的方式存在巨大的效率损失:

using StaticArrays

code_fast() = SMatrix{2,2}(1.0 , 1.0 , 1.0 , 1.0); code_fast(); @btime code_fast();
>> 0.026 ns (0 allocations: 0 bytes)

code_slow() = SMatrix{2,2}([1.0 1.0 ; 1.0 1.0]); code_slow(); @btime code_slow();
>> 45.371 ns (1 allocation: 112 bytes)
慢代码可以很容易地纠正,但是,通过设置
code_slow() = @SMatrix [1.0  1.0 ; 1.0  1.0]
它不再慢并且变得和 code_fast 一样快.问题在于使用 @SMatrix宏必须真正手动编写要转换的矩阵的分量,否则使用 rand , zerosones .如果这不能做到,那么除了使用 SMatrix{n,n} 之外,我找不到任何选择。 ,这会导致使用静态数组的速度很慢,它们变得毫无用处。
具体来说,我需要优化的函数类型看起来像
test(n,G,mat) = begin mat[1+n:2n,1:n] = G; mat end
哪里 G是在另一个函数内计算的复杂静态矩阵。我需要把这个矩阵塞进 mat作为一个块,我需要输出也是静态的(此操作执行了数十亿次)。通过在最后转换为静态的,即:
test_SA(n,G,mat)  = begin mat[1+n:2n,1:n] = G; SMatrix{2n,2n}(mat) end
我遇到了上述 SMatrix 的问题太慢:
n=2
G = @SMatrix ones(Float64,n,n)
mat = Matrix{Float64}(I,2n,2n)

test(n,G,mat); @btime test($n,$G,$mat); # 17.821 ns (0 allocations: 0 bytes)
test_SA(n,G,mat); @btime test_SA($n,$G,$mat_mm); # 1.825 μs (22 allocations: 1.36 KiB)
有人可以解释一下发生了什么,以及如何纠正它?我真的很想在这里使用静态数组,因为代码中的所有其他模块正是因为它们而运行得更快。

最佳答案

像名字一样表示大小的一个StaticArray应该是静态的,在您的代码中它是动态的而不是静态的。您的问题可以缩小为:

julia> @btime  SMatrix{2*$n,2*$n}($mat);
1.310 μs (22 allocations: 1.36 KiB)
该怎么办?第一个选项是具有在编译时已知的固定大小:
julia> @btime SMatrix{4,4}($mat);
1.599 ns (0 allocations: 0 bytes)
这并不总是很方便所以幸运的是还有另一个合理的选择 - 提前创建目标类型(并且可能会重复使用它 10 亿次)。
MySMatrix =  SMatrix{2n,2n}
一旦创建,它将非常快速:
julia> @btime $MySMatrix($mat)
1.799 ns (0 allocations: 0 bytes)
4×4 SArray{Tuple{4,4},Float64,2,16} with indices SOneTo(4)×SOneTo(4):
1.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 0.0 1.0
如果您正在生成静态数组,您还必须查看 sacollect这也快如 hell :
julia> @btime StaticArrays.sacollect($MySMatrix, i*j for i in 1:4, j in 1:4)
1.399 ns (0 allocations: 0 bytes)
4×4 SArray{Tuple{4,4},Int64,2,16} with indices SOneTo(4)×SOneTo(4):
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

关于optimization - 使用 StaticArrays 有效地填充矩阵中的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65524097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com