martinus / nanobench

Simple, fast, accurate single-header microbenchmarking functionality for C++11/14/17/20
https://nanobench.ankerl.com
MIT License
1.43k stars 82 forks source link

faster random shuffle #74

Closed martinus closed 1 year ago

martinus commented 2 years ago

This might work:

template <typename Container>
void Rng::shuffle(Container& container) noexcept {
    auto size = static_cast<uint32_t>(container.size());
    auto i = size;
    while (i > 2U) {
        using std::swap;
        auto n = operator()();
        auto b1 = (static_cast<uint32_t>(n) * static_cast<uint64_t>(i)) >> 32U;
        swap(container[--i], container[b1]);

        auto b2 = ((n >> 32U) * i) >> 32U;
        swap(container[--i], container[b2]);
    }
}
martinus commented 1 year ago

released in 4.3.8