Hi,
Brag points are up for grabs again. How can this code be made faster?
using BenchmarkTools
using Base.Test
struct Point{X,Y}
x::X
y::Y
end
function integral_squared(v::Vector{Point{X,Y}}) where {X,Y}
T = eltype(oneunit(X)*oneunit(Y)*oneunit(Y))
area = zero(T)
p1 = v[1]
for i in 2:length(v)
p2 = v[i]
dx = p2.x - p1.x
m = (p2.y - p1.y)/dx
b = p1.y
area += m/3*m*(dx*dx*dx) + b*m*(dx*dx) + b*b*(dx)
p1 = p2
end
return area
end
# Test code
N = 1_000_000
pwl = [Point(x, sin(x)) for x in linspace(0, pi, N)]
@test integral_squared(pwl) ā pi/2 atol=0.00001
println("Benchmarking:")
@btime integral_squared(pwl)
Brag points (genuine bullion to wear around your neck):
10: 10% faster
100: 25% faster
1000: 50% faster
Being it is not an easy challenge, the points are high. Most the time is spent on the area +=
line. The instructions per cycle is about 0.65 (according to tiptop
) and it could go as high as 4 on most systems so there is room for improvement. Hopefully weāll learn something new.
Thanks,
Glen