我正在考慮使用包 StaticArrays.jl 來提高我的代碼的性能。但是,我只使用陣列來存盤計算變數,并在設定某些條件后使用它們。因此,我將 SizedVector 型別與法線向量進行比較,但我不明白下面的代碼。我還嘗試了 StaticVector 并使用了 Setfield.jl 周圍的作業。
using StaticArrays, BenchmarkTools, Setfield
function copySized(n::Int64)
v = SizedVector{n, Int64}(zeros(n))
w = Vector{Int64}(undef, n)
for i in eachindex(v)
v[i] = i
end
for i in eachindex(v)
w[i] = v[i]
end
end
function copyStatic(n::Int64)
v = @SVector zeros(n)
w = Vector{Int64}(undef, n)
for i in eachindex(v)
@set v[i] = i
end
for i in eachindex(v)
w[i] = v[i]
end
end
function copynormal(n::Int64)
v = zeros(n)
w = Vector{Int64}(undef, n)
for i in eachindex(v)
v[i] = i
end
for i in eachindex(v)
w[i] = v[i]
end
end
n = 10
@btime copySized($n)
@btime copyStatic($n)
@btime copynormal($n)
3.950 μs (42 allocations: 2.08 KiB)
5.417 μs (98 allocations: 4.64 KiB)
78.822 ns (2 allocations: 288 bytes)
為什么 SizedVector 的情況確實有更多的分配,因此性能更差?我沒有正確使用 SizedVector 嗎?它至少不應該具有與普通陣列相同的性能嗎?
先感謝您。
朱莉婭話語的交叉帖子
uj5u.com熱心網友回復:
我覺得這是蘋果與橘子的比較(并且大小應該以靜態方式存盤)。更多說明性代碼可能如下所示:
function copySized(::Val{n}) where n
v = SizedVector{n}(1:n)
w = Vector{Int64}(undef, n)
w .= v
end
function copyStatic(::Val{n}) where n
v = SVector{n}(1:n)
w = Vector{Int64}(undef, n)
w .= v
end
function copynormal(n)
v = [1:n;]
w = Vector{Int64}(undef, n)
w .= v
end
現在基準測驗:
julia> n = 10
10
julia> @btime copySized(Val{$n}());
248.138 ns (1 allocation: 144 bytes)
julia> @btime copyStatic(Val{$n}());
251.507 ns (1 allocation: 144 bytes)
julia> @btime copynormal($n);
77.940 ns (2 allocations: 288 bytes)
julia>
julia>
julia> n = 1000
1000
julia> @btime copySized(Val{$n}());
840.000 ns (2 allocations: 7.95 KiB)
julia> @btime copyStatic(Val{$n}());
830.769 ns (2 allocations: 7.95 KiB)
julia> @btime copynormal($n);
1.100 μs (2 allocations: 15.88 KiB)
uj5u.com熱心網友回復:
@phipsgabler 是對的!當大小在編譯時靜態已知時,靜態大小的陣列具有其性能優勢。但是,我的陣列是動態調整大小的,大小 n 是運行時變數。
改變它會產生更明智的結果:
using StaticArrays, BenchmarkTools, Setfield
function copySized()
v = SizedVector{10, Float64}(zeros(10))
w = Vector{Float64}(undef, 10*2)
for i in eachindex(v)
v[i] = rand()
end
for i in eachindex(v)
j = i floor(Int64, 10/4)
w[j] = v[i]
end
end
function copyStatic()
v = @SVector zeros(10)
w = Vector{Int64}(undef, 10*2)
for i in eachindex(v)
@set v[i] = rand()
end
for i in eachindex(v)
j = i floor(Int64, 10/4)
w[j] = v[i]
end
end
function copynormal()
v = zeros(10)
w = Vector{Float64}(undef, 10*2)
for i in eachindex(v)
v[i] = rand()
end
for i in eachindex(v)
j = i floor(Int64, 10/4)
w[j] = v[i]
end
end
@btime copySized()
@btime copyStatic()
@btime copynormal()
110.162 ns (3 allocations: 512 bytes)
48.133 ns (1 allocation: 224 bytes)
92.045 ns (2 allocations: 368 bytes)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405981.html
標籤:
