Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions benchmarks/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ add_benchmark(efficient_nonlocking_print src/efficient_nonlocking_print.cpp)
add_benchmark(filesystem src/filesystem.cpp)
add_benchmark(find_and_count src/find_and_count.cpp)
add_benchmark(find_first_of src/find_first_of.cpp)
add_benchmark(has_single_bit src/has_single_bit.cpp)
add_benchmark(iota src/iota.cpp)
add_benchmark(locale_classic src/locale_classic.cpp)
add_benchmark(minmax_element src/minmax_element.cpp)
Expand Down
52 changes: 52 additions & 0 deletions benchmarks/src/has_single_bit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include <benchmark/benchmark.h>
#include <bit>
#include <cstdint>

#include <utility.hpp>

using namespace std;

template <typename T>
void bm_has_single_bit_if(benchmark::State& state) {
const auto random_v = random_vector<T>(8);
for (auto _ : state) {
benchmark::DoNotOptimize(random_v);
unsigned int count_true = 0;
unsigned int count_false = 0;
for (const auto& x : random_v) {
if (has_single_bit(x)) {
benchmark::DoNotOptimize(++count_true);
} else {
benchmark::DoNotOptimize(++count_false);
}
}
}
}

template <typename T>
void bm_has_single_bit(benchmark::State& state) {
const auto random_v = random_vector<T>(8);
for (auto _ : state) {
benchmark::DoNotOptimize(random_v);
unsigned int r = 0;
for (const auto& x : random_v) {
r += has_single_bit(x);
}
benchmark::DoNotOptimize(r);
}
}

BENCHMARK(bm_has_single_bit_if<uint8_t>);
BENCHMARK(bm_has_single_bit_if<uint16_t>);
BENCHMARK(bm_has_single_bit_if<uint32_t>);
BENCHMARK(bm_has_single_bit_if<uint64_t>);

BENCHMARK(bm_has_single_bit<uint8_t>);
BENCHMARK(bm_has_single_bit<uint16_t>);
BENCHMARK(bm_has_single_bit<uint32_t>);
BENCHMARK(bm_has_single_bit<uint64_t>);

BENCHMARK_MAIN();
2 changes: 1 addition & 1 deletion stl/inc/bit
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ _NODISCARD constexpr int countl_zero(_Ty _Val) noexcept;

_EXPORT_STD template <_Standard_unsigned_integral _Ty>
_NODISCARD constexpr bool has_single_bit(const _Ty _Val) noexcept {
return _Val != 0 && (_Val & (_Val - 1)) == 0;
return (_Val ^ (_Val - 1)) > _Val - 1;
}

inline void _Precondition_violation_in_bit_ceil() noexcept {}
Expand Down