Thread View: comp.lang.c++
3 messages
3 total messages
Started by Bonita Montero
Mon, 02 Nov 2026 09:24
Faster lower_bound / upper_bound
Author: Bonita Montero
Date: Mon, 02 Nov 2026 09:24
Date: Mon, 02 Nov 2026 09:24
47 lines
2633 bytes
2633 bytes
I wondered why lower_bound and upper_bound are almost twice as fast
with clang-cl than with MSVC. I inspected the code and MSVC didn't
use conditional moves (see below) and the non-predictible branches
did really hurt.
So I wrote two generic functions which do the same and make it easier
for MSVC to do the optimization. And it worked: The MSVC-code is only
slightly slower than the clang-cl-code with that.
#pragma once
#include <type_traits>
#include <functional>
template<typename Iterator, typename Ref, typename Cmp =
std::less<std::iter_value_t<Iterator>>>
inline Iterator xlower_bound( Iterator begin, Iterator end, const Ref
&value, Cmp cmp = Cmp() )
{
for( size_t n = end - begin; n; )
{
size_t
mid = n / 2,
nRight = n - mid - 1;
Iterator right = begin + mid + 1;
bool less = cmp( begin[mid], value );
begin = less ? right : begin;
n = less ? nRight : mid;
}
return begin;
}
template<typename Iterator, typename Ref, typename Cmp =
std::less<std::iter_value_t<Iterator>>>
inline Iterator xupper_bound( Iterator begin, Iterator end, const Ref
&value, Cmp cmp = Cmp() )
{
for( size_t n = end - begin; n; )
{
size_t
mid = n / 2,
nRight = n - mid - 1;
Iterator right = begin + mid + 1;
bool less = cmp( value, begin[mid] );
begin = less ? begin : right;
n = less ? mid : nRight;
}
return begin;
}
Re: Faster lower_bound / upper_bound
Author: Oodini
Date: Fri, 06 Nov 2026 22:50
Date: Fri, 06 Nov 2026 22:50
7 lines
1373 bytes
1373 bytes
Le 02/11/2026 à 10:24, Bonita Montero a écrit : > I wondered why lower_bound and upper_bound are almost twice as fast > with clang-cl than with MSVC. I inspected the code and MSVC didn't > use conditional moves (see below) and the non-predictible branches > did really hurt. Which version of MSVC ?
Re: Faster lower_bound / upper_bound
Author: Bonita Montero
Date: Sat, 07 Nov 2026 14:15
Date: Sat, 07 Nov 2026 14:15
13 lines
1784 bytes
1784 bytes
Am 06.11.2026 um 23:50 schrieb Oodini: > Le 02/11/2026 à 10:24, Bonita Montero a écrit : >> I wondered why lower_bound and upper_bound are almost twice as fast >> with clang-cl than with MSVC. I inspected the code and MSVC didn't >> use conditional moves (see below) and the non-predictible branches >> did really hurt. > Which version of MSVC ? 19.51.36260
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads