Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help the compiler vectorize ranges::iota #4647

Merged
merged 4 commits into from
May 20, 2024
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
21 changes: 17 additions & 4 deletions benchmarks/src/iota.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,24 @@
#include <numeric>
#include <vector>

template <class T>
enum class Alg {
Std,
Rng,
};

template <class T, Alg Algorithm>
void bm(benchmark::State& state) {
const auto size = static_cast<std::size_t>(state.range(0));

std::vector<T> a(size);

for (auto _ : state) {
std::iota(a.begin(), a.end(), T{22});
if constexpr (Algorithm == Alg::Std) {
std::iota(a.begin(), a.end(), T{22});
} else if constexpr (Algorithm == Alg::Rng) {
std::ranges::iota(a, T{22});
}

benchmark::DoNotOptimize(a);
}
}
Expand All @@ -23,7 +33,10 @@ void common_args(auto bm) {
bm->Arg(7)->Arg(18)->Arg(43)->Arg(131)->Arg(315)->Arg(1212);
}

BENCHMARK(bm<std::uint32_t>)->Apply(common_args);
BENCHMARK(bm<std::uint64_t>)->Apply(common_args);
BENCHMARK(bm<std::uint32_t, Alg::Std>)->Apply(common_args);
BENCHMARK(bm<std::uint64_t, Alg::Std>)->Apply(common_args);

BENCHMARK(bm<std::uint32_t, Alg::Rng>)->Apply(common_args);
BENCHMARK(bm<std::uint64_t, Alg::Rng>)->Apply(common_args);

BENCHMARK_MAIN();
18 changes: 18 additions & 0 deletions stl/inc/numeric
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,24 @@ namespace ranges {
_STL_INTERNAL_STATIC_ASSERT(weakly_incrementable<_Ty>);
_STL_INTERNAL_STATIC_ASSERT(indirectly_writable<_It, const _Ty&>);

if constexpr (_Iterator_is_contiguous<_It> && sized_sentinel_for<_Se, _It> && is_integral_v<_Ty>
&& sizeof(_Ty) >= 4) {
// TRANSITION, DevCom-10593477: help the compiler vectorize
const auto _Ptr = _To_address(_First);
const auto _Size = static_cast<size_t>(_Last - _First);

if (_STD _In_range<_Ty>(_Size)) {
const auto _Size_typed = static_cast<_Ty>(_Size);
for (_Ty _Ix = 0; _Ix != _Size_typed; ++_Ix) {
const _Ty _Const_val = _Val + _Ix;
_Ptr[_Ix] = _Const_val;
}

_Val += _Size_typed;
return _First + _Size;
}
}

const _Ty& _Const_val = _Val;
for (; _First != _Last; ++_First, (void) ++_Val) {
*_First = _Const_val;
Expand Down