[Reland][Runtimes] Merge 'compile_commands.json' files from runtimes build (#116303)
[llvm-project.git] / third-party / benchmark / test / perf_counters_test.cc
blob3cc593e629d806154441dc704d23553adb091aa8
1 #include <cstdarg>
2 #undef NDEBUG
4 #include "../src/commandlineflags.h"
5 #include "../src/perf_counters.h"
6 #include "benchmark/benchmark.h"
7 #include "output_test.h"
9 namespace benchmark {
11 BM_DECLARE_string(benchmark_perf_counters);
13 } // namespace benchmark
15 static void BM_Simple(benchmark::State& state) {
16 for (auto _ : state) {
17 auto iterations = double(state.iterations()) * double(state.iterations());
18 benchmark::DoNotOptimize(iterations);
21 BENCHMARK(BM_Simple);
22 ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Simple\",$"}});
24 const int kIters = 1000000;
26 void BM_WithoutPauseResume(benchmark::State& state) {
27 int n = 0;
29 for (auto _ : state) {
30 for (auto i = 0; i < kIters; ++i) {
31 n = 1 - n;
32 benchmark::DoNotOptimize(n);
37 BENCHMARK(BM_WithoutPauseResume);
38 ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_WithoutPauseResume\",$"}});
40 void BM_WithPauseResume(benchmark::State& state) {
41 int m = 0, n = 0;
43 for (auto _ : state) {
44 for (auto i = 0; i < kIters; ++i) {
45 n = 1 - n;
46 benchmark::DoNotOptimize(n);
49 state.PauseTiming();
50 for (auto j = 0; j < kIters; ++j) {
51 m = 1 - m;
52 benchmark::DoNotOptimize(m);
54 state.ResumeTiming();
58 BENCHMARK(BM_WithPauseResume);
60 ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_WithPauseResume\",$"}});
62 static void CheckSimple(Results const& e) {
63 CHECK_COUNTER_VALUE(e, double, "CYCLES", GT, 0);
66 double withoutPauseResumeInstrCount = 0.0;
67 double withPauseResumeInstrCount = 0.0;
69 static void SaveInstrCountWithoutResume(Results const& e) {
70 withoutPauseResumeInstrCount = e.GetAs<double>("INSTRUCTIONS");
73 static void SaveInstrCountWithResume(Results const& e) {
74 withPauseResumeInstrCount = e.GetAs<double>("INSTRUCTIONS");
77 CHECK_BENCHMARK_RESULTS("BM_Simple", &CheckSimple);
78 CHECK_BENCHMARK_RESULTS("BM_WithoutPauseResume", &SaveInstrCountWithoutResume);
79 CHECK_BENCHMARK_RESULTS("BM_WithPauseResume", &SaveInstrCountWithResume);
81 int main(int argc, char* argv[]) {
82 if (!benchmark::internal::PerfCounters::kSupported) {
83 return 0;
85 benchmark::FLAGS_benchmark_perf_counters = "CYCLES,INSTRUCTIONS";
86 benchmark::internal::PerfCounters::Initialize();
87 RunOutputTests(argc, argv);
89 BM_CHECK_GT(withPauseResumeInstrCount, kIters);
90 BM_CHECK_GT(withoutPauseResumeInstrCount, kIters);
91 BM_CHECK_LT(withPauseResumeInstrCount, 1.5 * withoutPauseResumeInstrCount);