[libcxx-commits] [libcxx] [libc++] Optimize bitset::to_string (PR #128832)
Nikolas Klauser via libcxx-commits
libcxx-commits at lists.llvm.org
Wed Feb 26 06:59:34 PST 2025
================
@@ -0,0 +1,115 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+
+#include "benchmark/benchmark.h"
+#include <bitset>
+#include <cmath>
+#include <cstddef>
+
+template <std::size_t N>
+struct GenerateBitset {
+ // Construct a bitset with p*N true bits
+ static std::bitset<N> generate(double p) {
+ std::bitset<N> b;
+ if (p <= 0.0)
+ return b;
+ if (p >= 1.0)
+ return ~b;
+
+ std::size_t num_ones = std::round(N * p);
+ if (num_ones == 0)
+ return b;
+
+ double step = static_cast<double>(N) / num_ones;
+ double error = 0.0;
+
+ std::size_t pos = 0;
+ for (std::size_t i = 0; i < num_ones; ++i) {
+ if (pos >= N)
+ break;
+ b.set(pos);
+ error += step;
+ pos += std::floor(error);
+ error -= std::floor(error);
+ }
+ return b;
+ }
+
----------------
philnik777 wrote:
I think having random data here is really important to check your current implementation, since it likely heavily depends on the branch predictor.
https://github.com/llvm/llvm-project/pull/128832
More information about the libcxx-commits
mailing list