1// Testing:
2//   State::PauseTiming()
3//   State::ResumeTiming()
4// Test that CHECK's within these function diagnose when they are called
5// outside of the KeepRunning() loop.
6//
7// NOTE: Users should NOT include or use src/check.h. This is only done in
8// order to test library internals.
9
10#include <cstdlib>
11#include <stdexcept>
12
13#include "../src/check.h"
14#include "benchmark/benchmark.h"
15
16#if defined(__GNUC__) && !defined(__EXCEPTIONS)
17#define TEST_HAS_NO_EXCEPTIONS
18#endif
19
20void TestHandler() {
21#ifndef TEST_HAS_NO_EXCEPTIONS
22  throw std::logic_error("");
23#else
24  std::abort();
25#endif
26}
27
28void try_invalid_pause_resume(benchmark::State& state) {
29#if !defined(TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) && \
30    !defined(TEST_HAS_NO_EXCEPTIONS)
31  try {
32    state.PauseTiming();
33    std::abort();
34  } catch (std::logic_error const&) {
35  }
36  try {
37    state.ResumeTiming();
38    std::abort();
39  } catch (std::logic_error const&) {
40  }
41#else
42  (void)state;  // avoid unused warning
43#endif
44}
45
46void BM_diagnostic_test(benchmark::State& state) {
47  static bool called_once = false;
48
49  if (called_once == false) try_invalid_pause_resume(state);
50
51  for (auto _ : state) {
52    auto iterations = state.iterations();
53    benchmark::DoNotOptimize(iterations);
54  }
55
56  if (called_once == false) try_invalid_pause_resume(state);
57
58  called_once = true;
59}
60BENCHMARK(BM_diagnostic_test);
61
62void BM_diagnostic_test_keep_running(benchmark::State& state) {
63  static bool called_once = false;
64
65  if (called_once == false) try_invalid_pause_resume(state);
66
67  while (state.KeepRunning()) {
68    auto iterations = state.iterations();
69    benchmark::DoNotOptimize(iterations);
70  }
71
72  if (called_once == false) try_invalid_pause_resume(state);
73
74  called_once = true;
75}
76BENCHMARK(BM_diagnostic_test_keep_running);
77
78int main(int argc, char* argv[]) {
79#ifdef NDEBUG
80  // This test is exercising functionality for debug builds, which are not
81  // available in release builds. Skip the test if we are in that environment
82  // to avoid a test failure.
83  std::cout << "Diagnostic test disabled in release build" << std::endl;
84  (void)argc;
85  (void)argv;
86#else
87  benchmark::internal::GetAbortHandler() = &TestHandler;
88  benchmark::Initialize(&argc, argv);
89  benchmark::RunSpecifiedBenchmarks();
90#endif
91}
92