I am writing some code to do geometric intersection tests using StaticArrays.jl. I would like to keep some benchmarks as I am developing and would like to know if I am benchmarking static arrays correctly.
The documentation for BenchmarkTools mentions that operations that can be simplified at compile time will not be measured properly, and that you therefore have to reference and dereference the interpolated variable. I think I am doing that properly below, however the measured output is still very fast for this operation (around 6 ns), so I am suspicious that I am not measuring the right thing.
Would the below benchmark correctly measure the execution speed of the BVH.intersection function, and would anyone be able to explain / point to a source on how this interpolation and referencing / dereferencing works?
using BenchmarkTools
using Revise, StaticArrays, LinearAlgebra
function benchmark_intersection()
for T in [Float64, Float32]
v₁ = SVector{3, T}(1.0, 0.0, 1.0)
v₂ = SVector{3, T}(-1.0, 1.0, 1.0)
v₃ = SVector{3, T}(-1.0, -1.0, 1.0)
O = SVector{3, T}(0.0, 0.0, 0.0)
direction = SVector{3, T}(0.0, 0.0, 1.0)
A = [-direction (v₂-v₁) (v₃-v₁)]
b = O - v₁
ray = Ray(O, direction)
triangle = Triangle(v₁, v₂, v₃)
println("Benchmarking $T")
display(@benchmark intersection($(Ref(ray))[], $(Ref(triangle))[]))
end
end
struct Ray{N, T}
origin::SVector{N, T}
direction::SVector{N, T}
end
struct Triangle{N, T}
v₁::SVector{N, T}
v₂::SVector{N, T}
v₃::SVector{N, T}
end
function intersection(ray::Ray{N, T}, triangle::Triangle{N, T}) :: IntersectionResult{N, T} where {N, T}
(; origin, direction) = ray
(; v₁, v₂, v₃) = triangle
A = [-direction (v₂-v₁) (v₃-v₁)]
b = origin - v₁
if det(A) ≈ 0
return IntersectionResult(false, nothing)
end
(t, _, _) = A \ b
point = origin + direction * t
return IntersectionResult(true, point)
end