format_benchmark.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2018 The Abseil Authors.
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // https://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #include <cstddef>
  14. #include <string>
  15. #include "absl/time/internal/test_util.h"
  16. #include "absl/time/time.h"
  17. #include "benchmark/benchmark.h"
  18. namespace {
  19. namespace {
  20. const char* const kFormats[] = {
  21. absl::RFC1123_full, // 0
  22. absl::RFC1123_no_wday, // 1
  23. absl::RFC3339_full, // 2
  24. absl::RFC3339_sec, // 3
  25. "%Y-%m-%d%ET%H:%M:%S", // 4
  26. "%Y-%m-%d", // 5
  27. };
  28. const int kNumFormats = sizeof(kFormats) / sizeof(kFormats[0]);
  29. } // namespace
  30. void BM_Format_FormatTime(benchmark::State& state) {
  31. const std::string fmt = kFormats[state.range(0)];
  32. state.SetLabel(fmt);
  33. const absl::TimeZone lax =
  34. absl::time_internal::LoadTimeZone("America/Los_Angeles");
  35. const absl::Time t =
  36. absl::FromCivil(absl::CivilSecond(1977, 6, 28, 9, 8, 7), lax) +
  37. absl::Nanoseconds(1);
  38. while (state.KeepRunning()) {
  39. benchmark::DoNotOptimize(absl::FormatTime(fmt, t, lax).length());
  40. }
  41. }
  42. BENCHMARK(BM_Format_FormatTime)->DenseRange(0, kNumFormats - 1);
  43. void BM_Format_ParseTime(benchmark::State& state) {
  44. const std::string fmt = kFormats[state.range(0)];
  45. state.SetLabel(fmt);
  46. const absl::TimeZone lax =
  47. absl::time_internal::LoadTimeZone("America/Los_Angeles");
  48. absl::Time t = absl::FromCivil(absl::CivilSecond(1977, 6, 28, 9, 8, 7), lax) +
  49. absl::Nanoseconds(1);
  50. const std::string when = absl::FormatTime(fmt, t, lax);
  51. std::string err;
  52. while (state.KeepRunning()) {
  53. benchmark::DoNotOptimize(absl::ParseTime(fmt, when, lax, &t, &err));
  54. }
  55. }
  56. BENCHMARK(BM_Format_ParseTime)->DenseRange(0, kNumFormats - 1);
  57. } // namespace