[libcxx-commits] [libcxx] [libc++] Optimize ranges::move{, _backward} for vector<bool>::iterator (PR #121109)

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Thu Feb 6 12:04:18 PST 2025


================
@@ -0,0 +1,55 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+#include <algorithm>
+#include <benchmark/benchmark.h>
+#include <vector>
+
+static void bm_ranges_move_vb(benchmark::State& state, bool aligned) {
+  auto n = state.range();
+  std::vector<bool> in(n, true);
+  std::vector<bool> out(aligned ? n : n + 8);
+  benchmark::DoNotOptimize(&in);
+  auto dst = aligned ? out.begin() : out.begin() + 4;
+  for (auto _ : state) {
+    benchmark::DoNotOptimize(std::ranges::move(in, dst));
+    benchmark::DoNotOptimize(&out);
+  }
+}
----------------
winner245 wrote:

As suggested, I have rewritten the benchmarks as well as the tests completely. I applied the suggested idea by switching the roles of the `in` and `out` vectors to ensure that we never move or read from a vector that is already in a moved-from state. 

For the un-aligned case, I made the vectors `in` and `out` the same size (which ensures `out` can always hold the elements moved from the input), and then passed a view of the input by dropping either the first or last 4 bits to the range algorithm:

```cpp
std::ranges::move(*in | std::views::drop(4), std::ranges::begin(*out));
std::ranges::move_backward(*in | std::views::take(n - 4), std::ranges::end(*out));
```
For the un-aligned non-range algorithms `std::move, move_backward`, I applied the same idea of equally-sized `in` and `out` vectors, adjusting the iterators of the input to drop the first or last 4 bits.

Finally, I reran the benchmarks and observed the same speed-ups.


https://github.com/llvm/llvm-project/pull/121109


More information about the libcxx-commits mailing list