Skip to content

Commit

Permalink
Help the compiler vectorize ranges::iota (#4647)
Browse files Browse the repository at this point in the history
Co-authored-by: Stephan T. Lavavej <[email protected]>
  • Loading branch information
AlexGuteniev and StephanTLavavej committed May 20, 2024
1 parent 14a90eb commit ccf9e1f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
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

0 comments on commit ccf9e1f

Please sign in to comment.