diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index 3df81c9..6088bff 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -65,6 +65,31 @@ end # Batched in-place benchmarks: a small grid of (v_kind, q_kind, n, m). # Auto vs hand-picked strategies, plus the queries_sorted = true fast path. # --------------------------------------------------------------------------- +# Warm-started walk: each query's hint is the previous answer, and consecutive +# queries move by a fraction of an interval (the interpolation-lookup pattern). +# BracketGallop's hit fast path is what this cell measures; LinearScan is the +# reference for a hint that is right most of the time. +SUITE["warm_walk"] = BenchmarkGroup() +let v = _make_v(:random_sorted, 100_000), rng = StableRNG(7), nq = 4096 + xs = Vector{Float64}(undef, nq) + x = v[1] + for k in 1:nq + i = clamp(searchsortedlast(v, x), 1, length(v) - 1) + x = clamp(x + (rand(rng) < 0.01 ? (rand(rng) - 0.5) * 200 : rand(rng) * 0.35) * (v[i + 1] - v[i]), v[1], v[end]) + xs[k] = x + end + function walk(strategy, v, xs) + idx = 1; s = 0 + for x in xs + idx = searchsorted_last(strategy, v, x, idx); s += idx + end + return s + end + for (name, strategy) in (("BracketGallop", BracketGallop()), ("LinearScan", LinearScan()), ("Auto", Auto())) + SUITE["warm_walk"][name] = @benchmarkable($walk($strategy, $v, $xs)) + end +end + SUITE["batched"] = BenchmarkGroup() for v_kind in (:uniform, :logspaced, :random_sorted), q_kind in (:dense, :sparse, :clustered), diff --git a/src/kernels.jl b/src/kernels.jl index 8951beb..7c83b71 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -301,18 +301,143 @@ end # Kernel: BracketGallop — bracketstrictlymonotonic + bounded binary search. # =========================================================================== +# The hinted kernels are one pass each: the two comparisons at the hint decide +# a hit (a correlated caller — an interpolation interval lookup feeding each +# answer back as the next hint — hits most of the time), and on a miss the +# gallop continues from what those comparisons established instead of +# starting over, doubling its step until it brackets the answer, then a +# bisection that knows one end of the bracket is a valid candidate finishes. +# The earlier two-stage form (`bracketstrictlymonotonic` + Base's bounded +# bisection) re-read the hint's neighbours on a miss and, on a hit, ran the +# bisection over a width-one bracket — two more comparisons and loads per +# query, which measured 2× on a warm-started interval search. Duplicates are +# handled by the predicates themselves: `searchsortedlast` asks for the last +# `v[i] ≤ x`, so an equal right neighbour is not a hit and the gallop moves on. + +# Largest `i` in `[lo, hi]` with `!lt(o, x, v[i])`, given that `lo` satisfies it. +@inline function _bisect_last_from(v::AbstractVector, x, lo, hi, o::Base.Order.Ordering) + @inbounds while lo < hi + m = lo + ((hi - lo + 1) >> 1) # upper midpoint, overflow-safe + if Base.Order.lt(o, x, v[m]) + hi = m - 1 + else + lo = m + end + end + return lo +end + +# Smallest `i` in `[lo, hi]` with `!lt(o, v[i], x)`, given that `hi` satisfies it. +@inline function _bisect_first_to(v::AbstractVector, x, lo, hi, o::Base.Order.Ordering) + @inbounds while lo < hi + m = lo + ((hi - lo) >> 1) # lower midpoint, overflow-safe + if Base.Order.lt(o, v[m], x) + lo = m + 1 + else + hi = m + end + end + return hi +end + @inline function _kernel_last_bracket_gallop( v::AbstractVector, x, hint::Integer, order::Base.Order.Ordering, ) - lo, hi = bracketstrictlymonotonic(v, x, hint, order) - return searchsortedlast(v, x, lo, hi, order) + bottom, top = firstindex(v), lastindex(v) + (bottom <= hint <= top) || return searchsortedlast(v, x, order) + g = convert(keytype(v), hint) + @inbounds if !Base.Order.lt(order, x, v[g]) + # v[g] ≤ x: the answer is at or after g. + g == top && return g + Base.Order.lt(order, x, v[g + 1]) && return g # hit + lo = g + 1 # v[lo] ≤ x + hi = top + u = one(lo) + while true + nxt = lo + u + nxt >= top && break # v[top] undecided; the bisection settles it + if Base.Order.lt(order, x, v[nxt]) + hi = nxt - 1 + break + end + lo = nxt + u += u + end + return _bisect_last_from(v, x, lo, hi, order) + else + # x < v[g]: the answer is before g. + g == bottom && return bottom - one(g) + hi = g - 1 # x < v[hi + 1] + u = one(hi) + local lo + while true + prv = hi - u + if prv <= bottom + Base.Order.lt(order, x, v[bottom]) && return bottom - one(g) + lo = bottom + break + end + if Base.Order.lt(order, x, v[prv]) + hi = prv - 1 + u += u + else + lo = prv # v[lo] ≤ x + break + end + end + return _bisect_last_from(v, x, lo, hi, order) + end end +# `searchsortedfirst` polarity: the hint is a hit when `v[hint - 1] < x ≤ v[hint]`; +# an earlier duplicate of `x` fails that test and the gallop moves left. @inline function _kernel_first_bracket_gallop( v::AbstractVector, x, hint::Integer, order::Base.Order.Ordering, ) - lo, hi = bracketstrictlymonotonic_first(v, x, hint, order) - return searchsortedfirst(v, x, lo, hi, order) + bottom, top = firstindex(v), lastindex(v) + (bottom <= hint <= top) || return searchsortedfirst(v, x, order) + g = convert(keytype(v), hint) + @inbounds if !Base.Order.lt(order, v[g], x) + # x ≤ v[g]: the answer is at or before g. + g == bottom && return g + Base.Order.lt(order, v[g - 1], x) && return g # hit + hi = g - 1 # x ≤ v[hi] + lo = bottom + u = one(hi) + while true + prv = hi - u + prv <= bottom && break # v[bottom] undecided; the bisection settles it + if Base.Order.lt(order, v[prv], x) + lo = prv + 1 + break + end + hi = prv + u += u + end + return _bisect_first_to(v, x, lo, hi, order) + else + # v[g] < x: the answer is after g. + g == top && return top + one(g) + lo = g + 1 # v[lo - 1] < x + u = one(lo) + local hi + while true + nxt = lo + u + if nxt >= top + Base.Order.lt(order, v[top], x) && return top + one(g) + hi = top + break + end + if Base.Order.lt(order, v[nxt], x) + lo = nxt + 1 + u += u + else + hi = nxt # x ≤ v[hi] + break + end + end + return _bisect_first_to(v, x, lo, hi, order) + end end # =========================================================================== diff --git a/src/strategies.jl b/src/strategies.jl index 85ed8ac..5cb3040 100644 --- a/src/strategies.jl +++ b/src/strategies.jl @@ -73,6 +73,14 @@ the hint; never worse than ~2 log₂ n comparisons. Maps to `KIND_BRACKET_GALLOP`. Falls back to [`BinaryBracket`](@ref) when no hint is supplied. + +When the hint is the answer (`v[hint] ≤ x < v[hint + 1]` for `searchsorted_last`, +`v[hint - 1] < x ≤ v[hint]` for `searchsorted_first`) the result is returned after +those two comparisons, so a caller that feeds each answer back as the next hint +pays for the bracket and the bisection only when the query leaves the interval. +For float vectors that ordering cost is then dominated by `isless` (the default +`Base.Order.Forward`), which also orders NaN and signed zeros; a vector without +NaN can pass `order = Base.Order.Lt(<)` for plain comparisons. """ struct BracketGallop <: SearchStrategy end diff --git a/test/core_tests.jl b/test/core_tests.jl index cfc8086..7f2b5ad 100644 --- a/test/core_tests.jl +++ b/test/core_tests.jl @@ -294,6 +294,38 @@ end end end +@safetestset "BracketGallop hint hit fast path" begin + using FindFirstFunctions: BracketGallop, searchsorted_last, searchsorted_first + using StableRNGs + + # The hit fast path returns the hint after two comparisons when it is the + # answer. It must agree with Base for every hint (in and out of range), for + # duplicates (an equal neighbour must fall through to the bisection), at both + # ends of the vector, and under a reverse ordering. + rng = StableRNG(2026) + for trial in 1:300 + n = rand(rng, 1:40) + v = sort!(rand(rng, Bool) ? rand(rng, n) .* 10 : round.(rand(rng, n) .* 10; digits = 0)) + for x in (v[rand(rng, 1:n)], v[rand(rng, 1:n)] + eps(10.0), rand(rng) * 12 - 1, -1.0, 11.0), + h in -2:(n + 2) + @test searchsorted_last(BracketGallop(), v, x, h) == searchsortedlast(v, x) + @test searchsorted_first(BracketGallop(), v, x, h) == searchsortedfirst(v, x) + end + v_rev = reverse(v) + for x in (v[rand(rng, 1:n)], rand(rng) * 12 - 1), h in (0, 1, (n + 1) ÷ 2, n, n + 1) + @test searchsorted_last(BracketGallop(), v_rev, x, h; order = Base.Order.Reverse) == + searchsortedlast(v_rev, x, Base.Order.Reverse) + @test searchsorted_first(BracketGallop(), v_rev, x, h; order = Base.Order.Reverse) == + searchsortedfirst(v_rev, x, Base.Order.Reverse) + end + end + + # Integer hint of a different width returns the vector's index type. + v = collect(1.0:10.0) + @test searchsorted_last(BracketGallop(), v, 3.5, Int32(3)) === 3 + @test searchsorted_first(BracketGallop(), v, 3.5, Int32(4)) === 4 +end + @safetestset "SearchStrategy dispatch (single query)" begin using FindFirstFunctions: SearchStrategy, LinearScan, BracketGallop, BinaryBracket, Auto,