I don’t know if you solved that some other way. But note that your function temp1
is using a global definition of elementLength
that is probably defined somewhere there to do:
edges = @SVector [vertices[v%elementLength+1]-vertices[v] for v in 1:elementLength];
If I am wrong, please someone correct me, but you cannot define a static vector with a variable length at run time like that. If you don’t have elmentLength
defined somewhere in the global scope at parse time, it returns the error:
julia> temp1(vertexList,elements)
┌ Error: Failed to revise /home/leandro/Drive/Work/JuliaPlay/ribeiro.jl
│ exception =
│ LoadError: UndefVarError: elementLength not defined
Edit: Actually I could make it run without the global definition of elementLength
by initializing the array as with the explicit type signature, as:
edges = SVector{elementLength,SVector{elementLength,Float64}}([vertices[v%elementLength+1]-vertices[v] for v in 1:elementLength])
But the function then gets much slower and allocates much more.
It was tricky to get rid of all allocations while keeping the function general for any element size, but I think this did the trick:
function temp3(vertexList::AbstractVector{SVector{N,T}},elements) where {N,T}
acc = zero(MVector{N,T})
for k in 1:size(elements,1)
vertices = vertexList[elements[k]]
for i in 1:N
edge = vertices[i%N+1] - vertices[i]
acc[i] += norm(edge)
end
end
return SVector{N,T}(acc)
end
julia> @btime temp3($vertexList,$elements)
4.223 μs (0 allocations: 0 bytes)
3-element SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
663.956508776588
656.6284760140031
Code
using LinearAlgebra
using StaticArrays
function temp3(vertexList::AbstractVector{SVector{N,T}},elements) where {N,T}
acc = zero(MVector{N,T})
for k in 1:size(elements,1)
vertices = vertexList[elements[k]]
for i in 1:N
edge = vertices[i%N+1] - vertices[i]
acc[i] += norm(edge)
end
end
return SVector{N,T}(acc)
end
using BenchmarkTools
N=1000
vertexList = [ rand(SVector{3,Float64}) for i in 1:N ]
elements = [ SVector(rand(1:N),rand(1:N),rand(1:N)) for i in 1:N ]
@btime temp3($vertexList,$elements)