1 #include "benchmark/benchmark.h"
2 #include <chrono>
3 #include <thread>
4
5 #if defined(NDEBUG)
6 #undef NDEBUG
7 #endif
8 #include <cassert>
9
BM_basic(benchmark::State & state)10 void BM_basic(benchmark::State& state) {
11 for (auto _ : state) {
12 }
13 }
14
BM_basic_slow(benchmark::State & state)15 void BM_basic_slow(benchmark::State& state) {
16 std::chrono::milliseconds sleep_duration(state.range(0));
17 for (auto _ : state) {
18 std::this_thread::sleep_for(
19 std::chrono::duration_cast<std::chrono::nanoseconds>(sleep_duration));
20 }
21 }
22
23 BENCHMARK(BM_basic);
24 BENCHMARK(BM_basic)->Arg(42);
25 BENCHMARK(BM_basic_slow)->Arg(10)->Unit(benchmark::kNanosecond);
26 BENCHMARK(BM_basic_slow)->Arg(100)->Unit(benchmark::kMicrosecond);
27 BENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kMillisecond);
28 BENCHMARK(BM_basic)->Range(1, 8);
29 BENCHMARK(BM_basic)->RangeMultiplier(2)->Range(1, 8);
30 BENCHMARK(BM_basic)->DenseRange(10, 15);
31 BENCHMARK(BM_basic)->Args({42, 42});
32 BENCHMARK(BM_basic)->Ranges({{64, 512}, {64, 512}});
33 BENCHMARK(BM_basic)->MinTime(0.7);
34 BENCHMARK(BM_basic)->UseRealTime();
35 BENCHMARK(BM_basic)->ThreadRange(2, 4);
36 BENCHMARK(BM_basic)->ThreadPerCpu();
37 BENCHMARK(BM_basic)->Repetitions(3);
38 BENCHMARK(BM_basic)
39 ->RangeMultiplier(std::numeric_limits<int>::max())
40 ->Range(std::numeric_limits<int64_t>::min(),
41 std::numeric_limits<int64_t>::max());
42
43 // Negative ranges
44 BENCHMARK(BM_basic)->Range(-64, -1);
45 BENCHMARK(BM_basic)->RangeMultiplier(4)->Range(-8, 8);
46 BENCHMARK(BM_basic)->DenseRange(-2, 2, 1);
47 BENCHMARK(BM_basic)->Ranges({{-64, 1}, {-8, -1}});
48
CustomArgs(benchmark::internal::Benchmark * b)49 void CustomArgs(benchmark::internal::Benchmark* b) {
50 for (int i = 0; i < 10; ++i) {
51 b->Arg(i);
52 }
53 }
54
55 BENCHMARK(BM_basic)->Apply(CustomArgs);
56
BM_explicit_iteration_count(benchmark::State & state)57 void BM_explicit_iteration_count(benchmark::State& state) {
58 // Test that benchmarks specified with an explicit iteration count are
59 // only run once.
60 static bool invoked_before = false;
61 assert(!invoked_before);
62 invoked_before = true;
63
64 // Test that the requested iteration count is respected.
65 assert(state.max_iterations == 42);
66 size_t actual_iterations = 0;
67 for (auto _ : state)
68 ++actual_iterations;
69 assert(state.iterations() == state.max_iterations);
70 assert(state.iterations() == 42);
71
72 }
73 BENCHMARK(BM_explicit_iteration_count)->Iterations(42);
74
75 BENCHMARK_MAIN();
76