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
15 #include "absl/random/internal/nanobenchmark.h"
16
17 #include "absl/base/internal/raw_logging.h"
18 #include "absl/strings/numbers.h"
19
20 namespace absl {
21 ABSL_NAMESPACE_BEGIN
22 namespace random_internal_nanobenchmark {
23 namespace {
24
Div(const void *,FuncInput in)25 uint64_t Div(const void*, FuncInput in) {
26 // Here we're measuring the throughput because benchmark invocations are
27 // independent.
28 const int64_t d1 = 0xFFFFFFFFFFll / int64_t(in); // IDIV
29 return d1;
30 }
31
32 template <size_t N>
MeasureDiv(const FuncInput (& inputs)[N])33 void MeasureDiv(const FuncInput (&inputs)[N]) {
34 Result results[N];
35 Params params;
36 params.max_evals = 6; // avoid test timeout
37 const size_t num_results = Measure(&Div, nullptr, inputs, N, results, params);
38 if (num_results == 0) {
39 ABSL_RAW_LOG(
40 WARNING,
41 "WARNING: Measurement failed, should not happen when using "
42 "PinThreadToCPU unless the region to measure takes > 1 second.\n");
43 return;
44 }
45 for (size_t i = 0; i < num_results; ++i) {
46 ABSL_RAW_LOG(INFO, "%5zu: %6.2f ticks; MAD=%4.2f%%\n", results[i].input,
47 results[i].ticks, results[i].variability * 100.0);
48 ABSL_RAW_CHECK(results[i].ticks != 0.0f, "Zero duration");
49 }
50 }
51
RunAll(const int argc,char * argv[])52 void RunAll(const int argc, char* argv[]) {
53 // Avoid migrating between cores - important on multi-socket systems.
54 int cpu = -1;
55 if (argc == 2) {
56 if (!SimpleAtoi(argv[1], &cpu)) {
57 ABSL_RAW_LOG(FATAL, "The optional argument must be a CPU number >= 0.\n");
58 }
59 }
60 PinThreadToCPU(cpu);
61
62 // unpredictable == 1 but the compiler doesn't know that.
63 const FuncInput unpredictable = argc != 999;
64 static const FuncInput inputs[] = {unpredictable * 10, unpredictable * 100};
65
66 MeasureDiv(inputs);
67 }
68
69 } // namespace
70 } // namespace random_internal_nanobenchmark
71 ABSL_NAMESPACE_END
72 } // namespace absl
73
main(int argc,char * argv[])74 int main(int argc, char* argv[]) {
75 absl::random_internal_nanobenchmark::RunAll(argc, argv);
76 return 0;
77 }
78