File indexing completed on 2026-09-15 09:32:04
0001 #ifndef BENCHMARK_H
0002 #define BENCHMARK_H
0003
0004 #include "exception.h"
0005 #include <fmt/core.h>
0006 #include <fstream>
0007 #include <iomanip>
0008 #include <iostream>
0009 #include <map>
0010 #include <nlohmann/json.hpp>
0011 #include <string_view>
0012 #include <vector>
0013 #include <string>
0014
0015 namespace common_bench {
0016
0017
0018
0019 struct TestDefinitionError : Exception {
0020 TestDefinitionError(std::string_view msg)
0021 : Exception(msg, "test_definition_error") {}
0022 };
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039 struct Test {
0040
0041
0042
0043
0044 Test(const std::map<std::string, std::string> &definition)
0045 : json(definition) {
0046
0047
0048 error();
0049
0050 for (const auto &field : {"name", "title", "description", "quantity",
0051 "target", "value", "result"}) {
0052 if (json.find(field) == json.end()) {
0053 throw TestDefinitionError{
0054 fmt::format("Error in test definition: field '{}' missing", field)};
0055 }
0056 }
0057
0058 if (json.find("weight") == json.end()) {
0059 json["weight"] = 1.0;
0060 }
0061 }
0062
0063
0064 void pass(double value) { update_result("pass", value); }
0065
0066 void fail(double value) { update_result("fail", value); }
0067
0068 void error(double value = 0) { update_result("error", value); }
0069
0070 nlohmann::json json;
0071
0072 private:
0073 void update_result(std::string_view status, double value) {
0074 json["result"] = status;
0075 json["value"] = value;
0076 }
0077 };
0078
0079
0080
0081
0082 inline void write_test(const std::vector<Test> &data, const std::string &fname) {
0083 nlohmann::json test;
0084 for (auto &entry : data) {
0085 test["tests"].push_back(entry.json);
0086 }
0087 std::cout << fmt::format("Writing test data to {}\n", fname);
0088 std::ofstream output_file(fname);
0089 output_file << std::setw(4) << test << "\n";
0090 }
0091
0092
0093
0094 inline void write_test(const Test &data, const std::string &fname) {
0095 std::vector<Test> vtd{data};
0096 write_test(vtd, fname);
0097 }
0098
0099 }
0100
0101 #endif