nanobenchmark_test.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2017 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/random/internal/nanobenchmark.h"
  15. #include "absl/base/internal/raw_logging.h"
  16. #include "absl/strings/numbers.h"
  17. namespace absl {
  18. ABSL_NAMESPACE_BEGIN
  19. namespace random_internal_nanobenchmark {
  20. namespace {
  21. uint64_t Div(const void*, FuncInput in) {
  22. // Here we're measuring the throughput because benchmark invocations are
  23. // independent.
  24. const int64_t d1 = 0xFFFFFFFFFFll / int64_t(in); // IDIV
  25. return d1;
  26. }
  27. template <size_t N>
  28. void MeasureDiv(const FuncInput (&inputs)[N]) {
  29. Result results[N];
  30. Params params;
  31. params.max_evals = 6; // avoid test timeout
  32. const size_t num_results = Measure(&Div, nullptr, inputs, N, results, params);
  33. if (num_results == 0) {
  34. ABSL_RAW_LOG(
  35. WARNING,
  36. "WARNING: Measurement failed, should not happen when using "
  37. "PinThreadToCPU unless the region to measure takes > 1 second.\n");
  38. return;
  39. }
  40. for (size_t i = 0; i < num_results; ++i) {
  41. ABSL_RAW_LOG(INFO, "%5zu: %6.2f ticks; MAD=%4.2f%%\n", results[i].input,
  42. results[i].ticks, results[i].variability * 100.0);
  43. ABSL_RAW_CHECK(results[i].ticks != 0.0f, "Zero duration");
  44. }
  45. }
  46. void RunAll(const int argc, char* argv[]) {
  47. // Avoid migrating between cores - important on multi-socket systems.
  48. int cpu = -1;
  49. if (argc == 2) {
  50. if (!absl::SimpleAtoi(argv[1], &cpu)) {
  51. ABSL_RAW_LOG(FATAL, "The optional argument must be a CPU number >= 0.\n");
  52. }
  53. }
  54. PinThreadToCPU(cpu);
  55. // unpredictable == 1 but the compiler doesn't know that.
  56. const FuncInput unpredictable = argc != 999;
  57. static const FuncInput inputs[] = {unpredictable * 10, unpredictable * 100};
  58. MeasureDiv(inputs);
  59. }
  60. } // namespace
  61. } // namespace random_internal_nanobenchmark
  62. ABSL_NAMESPACE_END
  63. } // namespace absl
  64. int main(int argc, char* argv[]) {
  65. absl::random_internal_nanobenchmark::RunAll(argc, argv);
  66. return 0;
  67. }