aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/restricted/google/benchmark/src/json_reporter.cc
blob: 6559dfd5e6a3eeaf9d8676a63a8be6f8bf52b4e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <iomanip>  // for setprecision
#include <iostream>
#include <limits>
#include <string>
#include <tuple>
#include <vector>

#include "benchmark/benchmark.h"
#include "complexity.h"
#include "string_util.h"
#include "timers.h"

namespace benchmark {
namespace {

std::string StrEscape(const std::string& s) {
  std::string tmp;
  tmp.reserve(s.size());
  for (char c : s) {
    switch (c) {
      case '\b':
        tmp += "\\b";
        break;
      case '\f':
        tmp += "\\f";
        break;
      case '\n':
        tmp += "\\n";
        break;
      case '\r':
        tmp += "\\r";
        break;
      case '\t':
        tmp += "\\t";
        break;
      case '\\':
        tmp += "\\\\";
        break;
      case '"':
        tmp += "\\\"";
        break;
      default:
        tmp += c;
        break;
    }
  }
  return tmp;
}

std::string FormatKV(std::string const& key, std::string const& value) {
  return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(),
                   StrEscape(value).c_str());
}

std::string FormatKV(std::string const& key, const char* value) {
  return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(),
                   StrEscape(value).c_str());
}

std::string FormatKV(std::string const& key, bool value) {
  return StrFormat("\"%s\": %s", StrEscape(key).c_str(),
                   value ? "true" : "false");
}

std::string FormatKV(std::string const& key, int64_t value) {
  std::stringstream ss;
  ss << '"' << StrEscape(key) << "\": " << value;
  return ss.str();
}

std::string FormatKV(std::string const& key, double value) {
  std::stringstream ss;
  ss << '"' << StrEscape(key) << "\": ";

  if (std::isnan(value))
    ss << (value < 0 ? "-" : "") << "NaN";
  else if (std::isinf(value))
    ss << (value < 0 ? "-" : "") << "Infinity";
  else {
    const auto max_digits10 =
        std::numeric_limits<decltype(value)>::max_digits10;
    const auto max_fractional_digits10 = max_digits10 - 1;
    ss << std::scientific << std::setprecision(max_fractional_digits10)
       << value;
  }
  return ss.str();
}

int64_t RoundDouble(double v) { return std::lround(v); }

}  // end namespace

bool JSONReporter::ReportContext(const Context& context) {
  std::ostream& out = GetOutputStream();

  out << "{\n";
  std::string inner_indent(2, ' ');

  // Open context block and print context information.
  out << inner_indent << "\"context\": {\n";
  std::string indent(4, ' ');

  std::string walltime_value = LocalDateTimeString();
  out << indent << FormatKV("date", walltime_value) << ",\n";

  out << indent << FormatKV("host_name", context.sys_info.name) << ",\n";

  if (Context::executable_name) {
    out << indent << FormatKV("executable", Context::executable_name) << ",\n";
  }

  CPUInfo const& info = context.cpu_info;
  out << indent << FormatKV("num_cpus", static_cast<int64_t>(info.num_cpus))
      << ",\n";
  out << indent
      << FormatKV("mhz_per_cpu",
                  RoundDouble(info.cycles_per_second / 1000000.0))
      << ",\n";
  if (CPUInfo::Scaling::UNKNOWN != info.scaling) {
    out << indent
        << FormatKV("cpu_scaling_enabled",
                    info.scaling == CPUInfo::Scaling::ENABLED ? true : false)
        << ",\n";
  }

  out << indent << "\"caches\": [\n";
  indent = std::string(6, ' ');
  std::string cache_indent(8, ' ');
  for (size_t i = 0; i < info.caches.size(); ++i) {
    auto& CI = info.caches[i];
    out << indent << "{\n";
    out << cache_indent << FormatKV("type", CI.type) << ",\n";
    out << cache_indent << FormatKV("level", static_cast<int64_t>(CI.level))
        << ",\n";
    out << cache_indent << FormatKV("size", static_cast<int64_t>(CI.size))
        << ",\n";
    out << cache_indent
        << FormatKV("num_sharing", static_cast<int64_t>(CI.num_sharing))
        << "\n";
    out << indent << "}";
    if (i != info.caches.size() - 1) out << ",";
    out << "\n";
  }
  indent = std::string(4, ' ');
  out << indent << "],\n";
  out << indent << "\"load_avg\": [";
  for (auto it = info.load_avg.begin(); it != info.load_avg.end();) {
    out << *it++;
    if (it != info.load_avg.end()) out << ",";
  }
  out << "],\n";

#if defined(NDEBUG)
  const char build_type[] = "release";
#else
  const char build_type[] = "debug";
#endif
  out << indent << FormatKV("library_build_type", build_type);

  std::map<std::string, std::string>* global_context =
      internal::GetGlobalContext();

  if (global_context != nullptr) {
    for (const auto& kv : *global_context) {
      out << ",\n";
      out << indent << FormatKV(kv.first, kv.second);
    }
  }
  out << "\n";

  // Close context block and open the list of benchmarks.
  out << inner_indent << "},\n";
  out << inner_indent << "\"benchmarks\": [\n";
  return true;
}

void JSONReporter::ReportRuns(std::vector<Run> const& reports) {
  if (reports.empty()) {
    return;
  }
  std::string indent(4, ' ');
  std::ostream& out = GetOutputStream();
  if (!first_report_) {
    out << ",\n";
  }
  first_report_ = false;

  for (auto it = reports.begin(); it != reports.end(); ++it) {
    out << indent << "{\n";
    PrintRunData(*it);
    out << indent << '}';
    auto it_cp = it;
    if (++it_cp != reports.end()) {
      out << ",\n";
    }
  }
}

void JSONReporter::Finalize() {
  // Close the list of benchmarks and the top level object.
  GetOutputStream() << "\n  ]\n}\n";
}

void JSONReporter::PrintRunData(Run const& run) {
  std::string indent(6, ' ');
  std::ostream& out = GetOutputStream();
  out << indent << FormatKV("name", run.benchmark_name()) << ",\n";
  out << indent << FormatKV("family_index", run.family_index) << ",\n";
  out << indent
      << FormatKV("per_family_instance_index", run.per_family_instance_index)
      << ",\n";
  out << indent << FormatKV("run_name", run.run_name.str()) << ",\n";
  out << indent << FormatKV("run_type", [&run]() -> const char* {
    switch (run.run_type) {
      case BenchmarkReporter::Run::RT_Iteration:
        return "iteration";
      case BenchmarkReporter::Run::RT_Aggregate:
        return "aggregate";
    }
    BENCHMARK_UNREACHABLE();
  }()) << ",\n";
  out << indent << FormatKV("repetitions", run.repetitions) << ",\n";
  if (run.run_type != BenchmarkReporter::Run::RT_Aggregate) {
    out << indent << FormatKV("repetition_index", run.repetition_index)
        << ",\n";
  }
  out << indent << FormatKV("threads", run.threads) << ",\n";
  if (run.run_type == BenchmarkReporter::Run::RT_Aggregate) {
    out << indent << FormatKV("aggregate_name", run.aggregate_name) << ",\n";
    out << indent << FormatKV("aggregate_unit", [&run]() -> const char* {
      switch (run.aggregate_unit) {
        case StatisticUnit::kTime:
          return "time";
        case StatisticUnit::kPercentage:
          return "percentage";
      }
      BENCHMARK_UNREACHABLE();
    }()) << ",\n";
  }
  if (internal::SkippedWithError == run.skipped) {
    out << indent << FormatKV("error_occurred", true) << ",\n";
    out << indent << FormatKV("error_message", run.skip_message) << ",\n";
  } else if (internal::SkippedWithMessage == run.skipped) {
    out << indent << FormatKV("skipped", true) << ",\n";
    out << indent << FormatKV("skip_message", run.skip_message) << ",\n";
  }
  if (!run.report_big_o && !run.report_rms) {
    out << indent << FormatKV("iterations", run.iterations) << ",\n";
    if (run.run_type != Run::RT_Aggregate ||
        run.aggregate_unit == StatisticUnit::kTime) {
      out << indent << FormatKV("real_time", run.GetAdjustedRealTime())
          << ",\n";
      out << indent << FormatKV("cpu_time", run.GetAdjustedCPUTime());
    } else {
      assert(run.aggregate_unit == StatisticUnit::kPercentage);
      out << indent << FormatKV("real_time", run.real_accumulated_time)
          << ",\n";
      out << indent << FormatKV("cpu_time", run.cpu_accumulated_time);
    }
    out << ",\n"
        << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit));
  } else if (run.report_big_o) {
    out << indent << FormatKV("cpu_coefficient", run.GetAdjustedCPUTime())
        << ",\n";
    out << indent << FormatKV("real_coefficient", run.GetAdjustedRealTime())
        << ",\n";
    out << indent << FormatKV("big_o", GetBigOString(run.complexity)) << ",\n";
    out << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit));
  } else if (run.report_rms) {
    out << indent << FormatKV("rms", run.GetAdjustedCPUTime());
  }

  for (auto& c : run.counters) {
    out << ",\n" << indent << FormatKV(c.first, c.second);
  }

  if (run.memory_result) {
    const MemoryManager::Result memory_result = *run.memory_result;
    out << ",\n" << indent << FormatKV("allocs_per_iter", run.allocs_per_iter);
    out << ",\n"
        << indent << FormatKV("max_bytes_used", memory_result.max_bytes_used);

    auto report_if_present = [&out, &indent](const std::string& label,
                                             int64_t val) {
      if (val != MemoryManager::TombstoneValue)
        out << ",\n" << indent << FormatKV(label, val);
    };

    report_if_present("total_allocated_bytes",
                      memory_result.total_allocated_bytes);
    report_if_present("net_heap_growth", memory_result.net_heap_growth);
  }

  if (!run.report_label.empty()) {
    out << ",\n" << indent << FormatKV("label", run.report_label);
  }
  out << '\n';
}

const int64_t MemoryManager::TombstoneValue =
    std::numeric_limits<int64_t>::max();

}  // end namespace benchmark