[libcxx-commits] [PATCH] D141614: [libc++] nth_element change to partial sort when range is really small

Zhikai Zeng via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Sat Jan 14 07:14:17 PST 2023


Backl1ght added a comment.

It seems like the improvement is too small to make sense in benchmark. But from the output of code bellow we can tell that this reduce some calculations.

  #include <algorithm>
  #include <iostream>
  #include <random>
  #include <vector>
  
  int main(int argc, char** argv) {
    const int REPETITIONS = 100'000;
    const int N = 7;
  
    int seed = 998244353;
    std::mt19937 rng(seed);
    int num_comp = 0;
    std::vector<int> a(N);
    for (int i = 0; i < REPETITIONS; ++i) {
      std::iota(a.begin(), a.end(), 0);
      std::shuffle(a.begin(), a.end(), rng);
  
      int k = rng() % N;
      std::nth_element(a.begin(), a.begin() + k, a.end(),
                       [&](int x, int y) -> bool {
                         ++num_comp;
                         return x < y;
                       });
    }
    std::cout << "num comp: " << num_comp << std::endl;
    return 0;
  }

output before: `num comp: 2100000`
output after: `num comp: 1597554`


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D141614/new/

https://reviews.llvm.org/D141614



More information about the libcxx-commits mailing list