JuliaMath / HCubature.jl

pure-Julia multidimensional h-adaptive integration
Other
148 stars 23 forks source link

buffer preallocation in `hcubature` #47

Closed maltezfaria closed 1 year ago

maltezfaria commented 1 year ago

Introduce the alloc_buf function to preallocate the BinaryMaxHeap buffer used in hcubature, and adapt the signature of hcubature to accept an optional buffer keyword argument (similar to what QuadGK currently provides).

This can be helpful when calling hcubature several times on similar functions:

julia> buffer = alloc_buf(;dimension=1)
julia> @btime hcubature(x -> cos(x[1]), (0,), (1,);buffer=$buffer)
  105.399 ns (0 allocations: 0 bytes)
(0.8414709848078966, 1.1102230246251565e-16)

julia> @btime hcubature(x -> cos(x[1]), (0,), (1,))
  151.451 ns (2 allocations: 400 bytes)
(0.8414709848078966, 1.1102230246251565e-16)

For more complex integrands or higher dimensions, the gain is usually minimal (but it reduces the allocations):

julia> buffer = alloc_buf(;dimension=2, range_type=Float64, domain_type=Float64)

julia> @btime hcubature(x -> sqrt(x[1])*x[2], (0,0), (2pi, pi);buffer=$buffer)
  2.504 μs (0 allocations: 0 bytes)
(51.81413988124638, 6.910421404114884e-7)

julia> @btime hcubature(x -> sqrt(x[1])*x[2], (0,0), (2pi, pi))
  2.724 μs (3 allocations: 2.86 KiB)
(51.81413988124638, 6.910421404114884e-7)
maltezfaria commented 1 year ago

Is there anything else needed for this PR? Thanks.

stevengj commented 1 year ago

Thanks!

maltezfaria commented 1 year ago

Would it be possible to tag a new minor release (1.5.2)?