bench_json_parse.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Parse-time micro-benchmark — Phase A v1.10 yyjson swap.
  2. //
  3. // Compares nlohmann::json::parse against smartbotic::db::parse_to_nlohmann
  4. // on a corpus of JSON documents loaded from a file (one document per line).
  5. // Not a regression gate — informational, run by hand to capture the
  6. // parse-speed delta of the Phase A swap.
  7. #include <algorithm>
  8. #include <chrono>
  9. #include <fstream>
  10. #include <iostream>
  11. #include <string>
  12. #include <vector>
  13. #include <nlohmann/json.hpp>
  14. #include "json_parse.hpp"
  15. int main(int argc, char** argv) {
  16. if (argc < 2) {
  17. std::cerr << "usage: bench_json_parse <path-to-json-corpus>\n"
  18. << " corpus = one JSON document per line\n";
  19. return 1;
  20. }
  21. std::ifstream f(argv[1]);
  22. if (!f) {
  23. std::cerr << "cannot open " << argv[1] << "\n";
  24. return 1;
  25. }
  26. std::vector<std::string> docs;
  27. std::string line;
  28. while (std::getline(f, line)) {
  29. if (!line.empty()) docs.push_back(line);
  30. }
  31. if (docs.empty()) {
  32. std::cerr << "empty corpus\n";
  33. return 1;
  34. }
  35. std::cerr << "corpus: " << docs.size() << " documents\n";
  36. constexpr int kIters = 5;
  37. auto bench = [&](const char* name, auto fn) {
  38. double best = 1e18;
  39. for (int i = 0; i < kIters; ++i) {
  40. auto t0 = std::chrono::steady_clock::now();
  41. size_t sink = 0;
  42. for (const auto& s : docs) {
  43. auto j = fn(s);
  44. sink += j.size();
  45. }
  46. auto t1 = std::chrono::steady_clock::now();
  47. double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
  48. best = std::min(best, ms);
  49. std::cerr << " " << name << " iter " << i << ": " << ms
  50. << " ms (sink=" << sink << ")\n";
  51. }
  52. return best;
  53. };
  54. double nl = bench("nlohmann", [](const std::string& s) {
  55. return nlohmann::json::parse(s);
  56. });
  57. double yy = bench("yyjson ", [](const std::string& s) {
  58. return smartbotic::db::parse_to_nlohmann(s);
  59. });
  60. std::cout << "best nlohmann: " << nl << " ms\n";
  61. std::cout << "best yyjson: " << yy << " ms\n";
  62. std::cout << "speedup: " << (nl / yy) << "x\n";
  63. return 0;
  64. }