[libcxx-commits] [libcxx] [libc++] Optimize search_n (PR #171389)
Louis Dionne via libcxx-commits
libcxx-commits at lists.llvm.org
Fri Dec 19 08:50:14 PST 2025
================
@@ -81,6 +81,54 @@ int main(int argc, char** argv) {
bm.operator()<std::list<int>>("rng::search_n(list<int>, pred) (no match)", ranges_search_n_pred);
}
+ // Benchmark {std,ranges}::search_n where the needle almost matches a lot.
+ {
+ auto bm = []<class Container>(std::string name, auto search_n) {
+ benchmark::RegisterBenchmark(
+ name,
+ [search_n](auto& st) {
+ std::size_t const size = st.range(0);
+ using ValueType = typename Container::value_type;
+ ValueType x = Generate<ValueType>::random();
+ ValueType y = random_different_from({x});
+ Container haystack(size, x);
+ std::size_t n = size / 10; // needle size is 10% of the haystack
+
+ // Make sure there are no actual matches
+ for (size_t i = 0; i < size; i += getRandomInteger<size_t>(1, n - 1)) {
+ *std::next(haystack.begin(), i) = y;
+ }
+
+ for ([[maybe_unused]] auto _ : st) {
+ benchmark::DoNotOptimize(haystack);
+ benchmark::DoNotOptimize(n);
+ benchmark::DoNotOptimize(y);
+ auto result = search_n(haystack.begin(), haystack.end(), n, x);
+ benchmark::DoNotOptimize(result);
+ }
+ })
+ ->Arg(1000) // non power-of-two
+ ->Arg(1024)
+ ->Arg(8192)
+ ->Arg(1 << 20);
----------------
ldionne wrote:
Let's pick some sizes that make sense to reduce the cost of running these benchmarks (and apply the change everywhere in this file).
```
->Arg(32)
->Arg(1024)
->Arg(8192)
```
https://github.com/llvm/llvm-project/pull/171389
More information about the libcxx-commits
mailing list