1 // Copyright 2019 Google LLC
2 // SPDX-License-Identifier: Apache-2.0
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
16 #include "hwy/nanobenchmark.h"
18 #ifndef __STDC_FORMAT_MACROS
19 #define __STDC_FORMAT_MACROS // before inttypes.h
27 #include "hwy/tests/test_util-inl.h"
32 // Governs duration of test; avoid timeout in debug builds.
33 #if HWY_IS_DEBUG_BUILD
34 constexpr size_t kMaxEvals
= 3;
36 constexpr size_t kMaxEvals
= 4;
39 FuncOutput
Div(const void*, FuncInput in
) {
40 // Here we're measuring the throughput because benchmark invocations are
41 // independent. Any dividend will do; the divisor is nonzero.
46 void MeasureDiv(const FuncInput (&inputs
)[N
]) {
47 printf("Measuring integer division (output on final two lines)\n");
50 params
.max_evals
= kMaxEvals
;
51 const size_t num_results
= Measure(&Div
, nullptr, inputs
, N
, results
, params
);
52 for (size_t i
= 0; i
< num_results
; ++i
) {
53 printf("%5" PRIu64
": %6.2f ticks; MAD=%4.2f%%\n",
54 static_cast<uint64_t>(results
[i
].input
), results
[i
].ticks
,
55 results
[i
].variability
* 100.0);
61 // A function whose runtime depends on rng.
62 FuncOutput
Random(const void* /*arg*/, FuncInput in
) {
63 const size_t r
= rng() & 0xF;
64 FuncOutput ret
= static_cast<FuncOutput
>(in
);
65 for (size_t i
= 0; i
< r
; ++i
) {
66 ret
/= ((rng() & 1) + 2);
71 // Ensure the measured variability is high.
73 void MeasureRandom(const FuncInput (&inputs
)[N
]) {
76 p
.max_evals
= kMaxEvals
;
78 const size_t num_results
= Measure(&Random
, nullptr, inputs
, N
, results
, p
);
79 for (size_t i
= 0; i
< num_results
; ++i
) {
80 NANOBENCHMARK_CHECK(results
[i
].variability
> 1E-3);
84 TEST(NanobenchmarkTest
, RunAll
) {
85 const int unpredictable
= Unpredictable1(); // == 1, unknown to compiler.
86 static const FuncInput inputs
[] = {static_cast<FuncInput
>(unpredictable
) + 2,
87 static_cast<FuncInput
>(unpredictable
+ 9)};
90 MeasureRandom(inputs
);