PageRenderTime 2603ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/rv32x-llvm/utils/benchmark/test/output_test_helper.cc

https://gitlab.com/williamwp/riscv-rv32x-llvm
C++ | 423 lines | 339 code | 47 blank | 37 comment | 61 complexity | 1eefe8ccf0aa2f982295c73b810a8e23 MD5 | raw file
  1. #include <iostream>
  2. #include <map>
  3. #include <memory>
  4. #include <sstream>
  5. #include <cstring>
  6. #include "../src/check.h" // NOTE: check.h is for internal use only!
  7. #include "../src/re.h" // NOTE: re.h is for internal use only
  8. #include "output_test.h"
  9. #include "../src/benchmark_api_internal.h"
  10. // ========================================================================= //
  11. // ------------------------------ Internals -------------------------------- //
  12. // ========================================================================= //
  13. namespace internal {
  14. namespace {
  15. using TestCaseList = std::vector<TestCase>;
  16. // Use a vector because the order elements are added matters during iteration.
  17. // std::map/unordered_map don't guarantee that.
  18. // For example:
  19. // SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}});
  20. // Substitute("%HelloWorld") // Always expands to Hello.
  21. using SubMap = std::vector<std::pair<std::string, std::string>>;
  22. TestCaseList& GetTestCaseList(TestCaseID ID) {
  23. // Uses function-local statics to ensure initialization occurs
  24. // before first use.
  25. static TestCaseList lists[TC_NumID];
  26. return lists[ID];
  27. }
  28. SubMap& GetSubstitutions() {
  29. // Don't use 'dec_re' from header because it may not yet be initialized.
  30. static std::string safe_dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?";
  31. static SubMap map = {
  32. {"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"},
  33. // human-readable float
  34. {"%hrfloat", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kMGTPEZYmunpfazy]?"},
  35. {"%int", "[ ]*[0-9]+"},
  36. {" %s ", "[ ]+"},
  37. {"%time", "[ ]*[0-9]{1,6} ns"},
  38. {"%console_report", "[ ]*[0-9]{1,6} ns [ ]*[0-9]{1,6} ns [ ]*[0-9]+"},
  39. {"%console_us_report", "[ ]*[0-9] us [ ]*[0-9] us [ ]*[0-9]+"},
  40. {"%csv_header",
  41. "name,iterations,real_time,cpu_time,time_unit,bytes_per_second,"
  42. "items_per_second,label,error_occurred,error_message"},
  43. {"%csv_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,,,"},
  44. {"%csv_us_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",us,,,,,"},
  45. {"%csv_bytes_report",
  46. "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + ",,,,"},
  47. {"%csv_items_report",
  48. "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,," + safe_dec_re + ",,,"},
  49. {"%csv_bytes_items_report",
  50. "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re +
  51. "," + safe_dec_re + ",,,"},
  52. {"%csv_label_report_begin", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,"},
  53. {"%csv_label_report_end", ",,"}};
  54. return map;
  55. }
  56. std::string PerformSubstitutions(std::string source) {
  57. SubMap const& subs = GetSubstitutions();
  58. using SizeT = std::string::size_type;
  59. for (auto const& KV : subs) {
  60. SizeT pos;
  61. SizeT next_start = 0;
  62. while ((pos = source.find(KV.first, next_start)) != std::string::npos) {
  63. next_start = pos + KV.second.size();
  64. source.replace(pos, KV.first.size(), KV.second);
  65. }
  66. }
  67. return source;
  68. }
  69. void CheckCase(std::stringstream& remaining_output, TestCase const& TC,
  70. TestCaseList const& not_checks) {
  71. std::string first_line;
  72. bool on_first = true;
  73. std::string line;
  74. while (remaining_output.eof() == false) {
  75. CHECK(remaining_output.good());
  76. std::getline(remaining_output, line);
  77. if (on_first) {
  78. first_line = line;
  79. on_first = false;
  80. }
  81. for (const auto& NC : not_checks) {
  82. CHECK(!NC.regex->Match(line))
  83. << "Unexpected match for line \"" << line << "\" for MR_Not regex \""
  84. << NC.regex_str << "\""
  85. << "\n actual regex string \"" << TC.substituted_regex << "\""
  86. << "\n started matching near: " << first_line;
  87. }
  88. if (TC.regex->Match(line)) return;
  89. CHECK(TC.match_rule != MR_Next)
  90. << "Expected line \"" << line << "\" to match regex \"" << TC.regex_str
  91. << "\""
  92. << "\n actual regex string \"" << TC.substituted_regex << "\""
  93. << "\n started matching near: " << first_line;
  94. }
  95. CHECK(remaining_output.eof() == false)
  96. << "End of output reached before match for regex \"" << TC.regex_str
  97. << "\" was found"
  98. << "\n actual regex string \"" << TC.substituted_regex << "\""
  99. << "\n started matching near: " << first_line;
  100. }
  101. void CheckCases(TestCaseList const& checks, std::stringstream& output) {
  102. std::vector<TestCase> not_checks;
  103. for (size_t i = 0; i < checks.size(); ++i) {
  104. const auto& TC = checks[i];
  105. if (TC.match_rule == MR_Not) {
  106. not_checks.push_back(TC);
  107. continue;
  108. }
  109. CheckCase(output, TC, not_checks);
  110. not_checks.clear();
  111. }
  112. }
  113. class TestReporter : public benchmark::BenchmarkReporter {
  114. public:
  115. TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)
  116. : reporters_(reps) {}
  117. virtual bool ReportContext(const Context& context) {
  118. bool last_ret = false;
  119. bool first = true;
  120. for (auto rep : reporters_) {
  121. bool new_ret = rep->ReportContext(context);
  122. CHECK(first || new_ret == last_ret)
  123. << "Reports return different values for ReportContext";
  124. first = false;
  125. last_ret = new_ret;
  126. }
  127. (void)first;
  128. return last_ret;
  129. }
  130. void ReportRuns(const std::vector<Run>& report) {
  131. for (auto rep : reporters_) rep->ReportRuns(report);
  132. }
  133. void Finalize() {
  134. for (auto rep : reporters_) rep->Finalize();
  135. }
  136. private:
  137. std::vector<benchmark::BenchmarkReporter *> reporters_;
  138. };
  139. }
  140. } // end namespace internal
  141. // ========================================================================= //
  142. // -------------------------- Results checking ----------------------------- //
  143. // ========================================================================= //
  144. namespace internal {
  145. // Utility class to manage subscribers for checking benchmark results.
  146. // It works by parsing the CSV output to read the results.
  147. class ResultsChecker {
  148. public:
  149. struct PatternAndFn : public TestCase { // reusing TestCase for its regexes
  150. PatternAndFn(const std::string& rx, ResultsCheckFn fn_)
  151. : TestCase(rx), fn(fn_) {}
  152. ResultsCheckFn fn;
  153. };
  154. std::vector< PatternAndFn > check_patterns;
  155. std::vector< Results > results;
  156. std::vector< std::string > field_names;
  157. void Add(const std::string& entry_pattern, ResultsCheckFn fn);
  158. void CheckResults(std::stringstream& output);
  159. private:
  160. void SetHeader_(const std::string& csv_header);
  161. void SetValues_(const std::string& entry_csv_line);
  162. std::vector< std::string > SplitCsv_(const std::string& line);
  163. };
  164. // store the static ResultsChecker in a function to prevent initialization
  165. // order problems
  166. ResultsChecker& GetResultsChecker() {
  167. static ResultsChecker rc;
  168. return rc;
  169. }
  170. // add a results checker for a benchmark
  171. void ResultsChecker::Add(const std::string& entry_pattern, ResultsCheckFn fn) {
  172. check_patterns.emplace_back(entry_pattern, fn);
  173. }
  174. // check the results of all subscribed benchmarks
  175. void ResultsChecker::CheckResults(std::stringstream& output) {
  176. // first reset the stream to the start
  177. {
  178. auto start = std::ios::streampos(0);
  179. // clear before calling tellg()
  180. output.clear();
  181. // seek to zero only when needed
  182. if(output.tellg() > start) output.seekg(start);
  183. // and just in case
  184. output.clear();
  185. }
  186. // now go over every line and publish it to the ResultsChecker
  187. std::string line;
  188. bool on_first = true;
  189. while (output.eof() == false) {
  190. CHECK(output.good());
  191. std::getline(output, line);
  192. if (on_first) {
  193. SetHeader_(line); // this is important
  194. on_first = false;
  195. continue;
  196. }
  197. SetValues_(line);
  198. }
  199. // finally we can call the subscribed check functions
  200. for(const auto& p : check_patterns) {
  201. VLOG(2) << "--------------------------------\n";
  202. VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n";
  203. for(const auto& r : results) {
  204. if(!p.regex->Match(r.name)) {
  205. VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n";
  206. continue;
  207. } else {
  208. VLOG(2) << p.regex_str << " is matched by " << r.name << "\n";
  209. }
  210. VLOG(1) << "Checking results of " << r.name << ": ... \n";
  211. p.fn(r);
  212. VLOG(1) << "Checking results of " << r.name << ": OK.\n";
  213. }
  214. }
  215. }
  216. // prepare for the names in this header
  217. void ResultsChecker::SetHeader_(const std::string& csv_header) {
  218. field_names = SplitCsv_(csv_header);
  219. }
  220. // set the values for a benchmark
  221. void ResultsChecker::SetValues_(const std::string& entry_csv_line) {
  222. if(entry_csv_line.empty()) return; // some lines are empty
  223. CHECK(!field_names.empty());
  224. auto vals = SplitCsv_(entry_csv_line);
  225. CHECK_EQ(vals.size(), field_names.size());
  226. results.emplace_back(vals[0]); // vals[0] is the benchmark name
  227. auto &entry = results.back();
  228. for (size_t i = 1, e = vals.size(); i < e; ++i) {
  229. entry.values[field_names[i]] = vals[i];
  230. }
  231. }
  232. // a quick'n'dirty csv splitter (eliminating quotes)
  233. std::vector< std::string > ResultsChecker::SplitCsv_(const std::string& line) {
  234. std::vector< std::string > out;
  235. if(line.empty()) return out;
  236. if(!field_names.empty()) out.reserve(field_names.size());
  237. size_t prev = 0, pos = line.find_first_of(','), curr = pos;
  238. while(pos != line.npos) {
  239. CHECK(curr > 0);
  240. if(line[prev] == '"') ++prev;
  241. if(line[curr-1] == '"') --curr;
  242. out.push_back(line.substr(prev, curr-prev));
  243. prev = pos + 1;
  244. pos = line.find_first_of(',', pos + 1);
  245. curr = pos;
  246. }
  247. curr = line.size();
  248. if(line[prev] == '"') ++prev;
  249. if(line[curr-1] == '"') --curr;
  250. out.push_back(line.substr(prev, curr-prev));
  251. return out;
  252. }
  253. } // end namespace internal
  254. size_t AddChecker(const char* bm_name, ResultsCheckFn fn)
  255. {
  256. auto &rc = internal::GetResultsChecker();
  257. rc.Add(bm_name, fn);
  258. return rc.results.size();
  259. }
  260. int Results::NumThreads() const {
  261. auto pos = name.find("/threads:");
  262. if(pos == name.npos) return 1;
  263. auto end = name.find('/', pos + 9);
  264. std::stringstream ss;
  265. ss << name.substr(pos + 9, end);
  266. int num = 1;
  267. ss >> num;
  268. CHECK(!ss.fail());
  269. return num;
  270. }
  271. double Results::GetTime(BenchmarkTime which) const {
  272. CHECK(which == kCpuTime || which == kRealTime);
  273. const char *which_str = which == kCpuTime ? "cpu_time" : "real_time";
  274. double val = GetAs< double >(which_str);
  275. auto unit = Get("time_unit");
  276. CHECK(unit);
  277. if(*unit == "ns") {
  278. return val * 1.e-9;
  279. } else if(*unit == "us") {
  280. return val * 1.e-6;
  281. } else if(*unit == "ms") {
  282. return val * 1.e-3;
  283. } else if(*unit == "s") {
  284. return val;
  285. } else {
  286. CHECK(1 == 0) << "unknown time unit: " << *unit;
  287. return 0;
  288. }
  289. }
  290. // ========================================================================= //
  291. // -------------------------- Public API Definitions------------------------ //
  292. // ========================================================================= //
  293. TestCase::TestCase(std::string re, int rule)
  294. : regex_str(std::move(re)),
  295. match_rule(rule),
  296. substituted_regex(internal::PerformSubstitutions(regex_str)),
  297. regex(std::make_shared<benchmark::Regex>()) {
  298. std::string err_str;
  299. regex->Init(substituted_regex,& err_str);
  300. CHECK(err_str.empty()) << "Could not construct regex \"" << substituted_regex
  301. << "\""
  302. << "\n originally \"" << regex_str << "\""
  303. << "\n got error: " << err_str;
  304. }
  305. int AddCases(TestCaseID ID, std::initializer_list<TestCase> il) {
  306. auto& L = internal::GetTestCaseList(ID);
  307. L.insert(L.end(), il);
  308. return 0;
  309. }
  310. int SetSubstitutions(
  311. std::initializer_list<std::pair<std::string, std::string>> il) {
  312. auto& subs = internal::GetSubstitutions();
  313. for (auto KV : il) {
  314. bool exists = false;
  315. KV.second = internal::PerformSubstitutions(KV.second);
  316. for (auto& EKV : subs) {
  317. if (EKV.first == KV.first) {
  318. EKV.second = std::move(KV.second);
  319. exists = true;
  320. break;
  321. }
  322. }
  323. if (!exists) subs.push_back(std::move(KV));
  324. }
  325. return 0;
  326. }
  327. void RunOutputTests(int argc, char* argv[]) {
  328. using internal::GetTestCaseList;
  329. benchmark::Initialize(&argc, argv);
  330. auto options = benchmark::internal::GetOutputOptions(/*force_no_color*/true);
  331. benchmark::ConsoleReporter CR(options);
  332. benchmark::JSONReporter JR;
  333. benchmark::CSVReporter CSVR;
  334. struct ReporterTest {
  335. const char* name;
  336. std::vector<TestCase>& output_cases;
  337. std::vector<TestCase>& error_cases;
  338. benchmark::BenchmarkReporter& reporter;
  339. std::stringstream out_stream;
  340. std::stringstream err_stream;
  341. ReporterTest(const char* n, std::vector<TestCase>& out_tc,
  342. std::vector<TestCase>& err_tc,
  343. benchmark::BenchmarkReporter& br)
  344. : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {
  345. reporter.SetOutputStream(&out_stream);
  346. reporter.SetErrorStream(&err_stream);
  347. }
  348. } TestCases[] = {
  349. {"ConsoleReporter", GetTestCaseList(TC_ConsoleOut),
  350. GetTestCaseList(TC_ConsoleErr), CR},
  351. {"JSONReporter", GetTestCaseList(TC_JSONOut), GetTestCaseList(TC_JSONErr),
  352. JR},
  353. {"CSVReporter", GetTestCaseList(TC_CSVOut), GetTestCaseList(TC_CSVErr),
  354. CSVR},
  355. };
  356. // Create the test reporter and run the benchmarks.
  357. std::cout << "Running benchmarks...\n";
  358. internal::TestReporter test_rep({&CR, &JR, &CSVR});
  359. benchmark::RunSpecifiedBenchmarks(&test_rep);
  360. for (auto& rep_test : TestCases) {
  361. std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n";
  362. std::string banner(msg.size() - 1, '-');
  363. std::cout << banner << msg << banner << "\n";
  364. std::cerr << rep_test.err_stream.str();
  365. std::cout << rep_test.out_stream.str();
  366. internal::CheckCases(rep_test.error_cases, rep_test.err_stream);
  367. internal::CheckCases(rep_test.output_cases, rep_test.out_stream);
  368. std::cout << "\n";
  369. }
  370. // now that we know the output is as expected, we can dispatch
  371. // the checks to subscribees.
  372. auto &csv = TestCases[2];
  373. // would use == but gcc spits a warning
  374. CHECK(std::strcmp(csv.name, "CSVReporter") == 0);
  375. internal::GetResultsChecker().CheckResults(csv.out_stream);
  376. }