diff --git a/libcxx/include/__algorithm/count_if.h b/libcxx/include/__algorithm/count_if.h index 25782069d0327..b08e5c27e43b6 100644 --- a/libcxx/include/__algorithm/count_if.h +++ b/libcxx/include/__algorithm/count_if.h @@ -10,6 +10,7 @@ #ifndef _LIBCPP___ALGORITHM_COUNT_IF_H #define _LIBCPP___ALGORITHM_COUNT_IF_H +#include <__algorithm/for_each.h> #include <__config> #include <__iterator/iterator_traits.h> @@ -21,12 +22,13 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 -typename iterator_traits<_InputIterator>::difference_type -count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) { + typename iterator_traits<_InputIterator>::difference_type + count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) { typename iterator_traits<_InputIterator>::difference_type __r(0); - for (; __first != __last; ++__first) - if (__pred(*__first)) + std::for_each(__first, __last, [&__r, &__pred](const auto& __val) mutable { + if (__pred(__val)) ++__r; + }); return __r; } diff --git a/libcxx/test/benchmarks/CMakeLists.txt b/libcxx/test/benchmarks/CMakeLists.txt index 616cf0ff8d237..5d946d9114b80 100644 --- a/libcxx/test/benchmarks/CMakeLists.txt +++ b/libcxx/test/benchmarks/CMakeLists.txt @@ -110,6 +110,7 @@ endfunction() set(BENCHMARK_TESTS algorithms.partition_point.bench.cpp algorithms/count.bench.cpp + algorithms/count_if.bench.cpp algorithms/equal.bench.cpp algorithms/find.bench.cpp algorithms/fill.bench.cpp diff --git a/libcxx/test/benchmarks/algorithms/count_if.bench.cpp b/libcxx/test/benchmarks/algorithms/count_if.bench.cpp new file mode 100644 index 0000000000000..785d6eec61984 --- /dev/null +++ b/libcxx/test/benchmarks/algorithms/count_if.bench.cpp @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#include +#include +#include + +static void bm_deque_count_if(benchmark::State& state) { + std::deque deque1(state.range(), '1'); + for (auto _ : state) { + benchmark::DoNotOptimize(deque1); + benchmark::DoNotOptimize(std::count_if(deque1.begin(), deque1.end(), [](char& v) { return v == '0'; })); + } +} +BENCHMARK(bm_deque_count_if)->DenseRange(1, 8)->Range(16, 1 << 20); + +BENCHMARK_MAIN();