I have the following code:
using BenchmarkTools, StaticArrays
if ! @isdefined SEGMENTS
const SEGMENTS = 6
end
# Type definitions
const SimFloat = Float64
const Vec3 = MVector{3, SimFloat}
function create_state()
pos = zeros(SVector{SEGMENTS+1, Vec3})
pos[1] .= [1.0,2,3]
vel = zeros(SVector{SEGMENTS+1, Vec3})
y = reduce(vcat, vcat(pos, vel))
end
function unpack(y)
part = reshape(y, Size(3, SEGMENTS+1, 2))
pos1 = part[:,:,1]
pos2 = [SVector(pos1[:,i]) for i in 1:SEGMENTS+1]
end
state = create_state()
display(unpack(state))
display(@benchmark unpack(y) setup = (y = create_state()))
It has the following output:
julia> include("src/test.jl")
7-element Vector{SVector{3, Float64}}:
[1.0, 2.0, 3.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
BenchmarkTools.Trial:
memory estimate: 432 bytes
allocs estimate: 2
--------------
minimum time: 52.806 ns (0.00% GC)
median time: 55.680 ns (0.00% GC)
mean time: 59.781 ns (4.43% GC)
maximum time: 541.337 ns (77.31% GC)
--------------
samples: 10000
evals/sample: 985
There are two things I want to improve:
- the function unpack should return an SVector of SVectors. How can I achieve that?
- the function unpack shall NOT allocate
Any ideas?