compare.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <library/cpp/case_insensitive_string/ut_gtest/util/locale_guard.h>
  2. #include <library/cpp/case_insensitive_string/case_insensitive_string.h>
  3. #include <benchmark/benchmark.h>
  4. #include <util/generic/string.h>
  5. #include <util/random/random.h>
  6. #include <array>
  7. #include <cerrno>
  8. #include <clocale>
  9. #include <cstring>
  10. namespace {
  11. template <typename TStrBuf>
  12. void BenchmarkCompare(benchmark::State& state, TStrBuf s1, TStrBuf s2) {
  13. for (auto _ : state) {
  14. benchmark::DoNotOptimize(s1);
  15. benchmark::DoNotOptimize(s2);
  16. auto cmp = s1.compare(s2);
  17. benchmark::DoNotOptimize(cmp);
  18. }
  19. }
  20. char RandomPrintableChar() {
  21. while (true) {
  22. unsigned char c = RandomNumber(127u);
  23. if (std::isprint(c)) {
  24. return c;
  25. }
  26. }
  27. }
  28. const std::array<const char*, 2> Locales = {
  29. "C",
  30. "ru_RU.CP1251",
  31. };
  32. }
  33. template <typename TStrBuf>
  34. void CompareEqualStrings(benchmark::State& state) {
  35. SetRandomSeed(123);
  36. size_t n = state.range(0);
  37. size_t locIndex = state.range(1);
  38. TLocaleGuard loc(Locales[locIndex]);
  39. if (loc.Error()) {
  40. state.SkipWithMessage(TString::Join(Locales[locIndex], " locale is not available: ", loc.Error()));
  41. return;
  42. }
  43. TString s1(Reserve(n)), s2(Reserve(n));
  44. for (size_t i = 0; i < n; ++i) {
  45. auto c = RandomPrintableChar();
  46. s1.push_back(std::toupper(c));
  47. s2.push_back(std::tolower(c));
  48. }
  49. BenchmarkCompare(state, TStrBuf(s1.data(), s1.size()), TStrBuf(s2.data(), s2.size()));
  50. }
  51. #define BENCH_ARGS ArgNames({"strlen", "locale"})->ArgsProduct({{2, 4, 8, 16, 32, 64}, {0, 1}})
  52. BENCHMARK(CompareEqualStrings<TCaseInsensitiveStringBuf>)->BENCH_ARGS;
  53. BENCHMARK(CompareEqualStrings<TCaseInsensitiveAsciiStringBuf>)->BENCH_ARGS;
  54. #undef BENCH_ARGS