benchmark_serialize.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. Minetest
  3. Copyright (C) 2022 Minetest Authors
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "benchmark_setup.h"
  17. #include "util/serialize.h"
  18. #include <sstream>
  19. #include <ios>
  20. // Builds a string of exactly `length` characters by repeating `s` (rest cut off)
  21. static std::string makeRepeatTo(const std::string &s, size_t length)
  22. {
  23. std::string v;
  24. v.reserve(length + s.size());
  25. for (size_t i = 0; i < length; i += s.size()) {
  26. v += s;
  27. }
  28. v.resize(length);
  29. return v;
  30. }
  31. #define BENCH3(_label, _chars, _length, _lengthlabel) \
  32. BENCHMARK_ADVANCED("serializeJsonStringIfNeeded_" _lengthlabel "_" _label)(Catch::Benchmark::Chronometer meter) { \
  33. std::string s = makeRepeatTo(_chars, _length); \
  34. meter.measure([&] { return serializeJsonStringIfNeeded(s); }); \
  35. }; \
  36. BENCHMARK_ADVANCED("deSerializeJsonStringIfNeeded_" _lengthlabel "_" _label)(Catch::Benchmark::Chronometer meter) { \
  37. std::string s = makeRepeatTo(_chars, _length); \
  38. std::string serialized = serializeJsonStringIfNeeded(s); \
  39. std::istringstream is(serialized, std::ios::binary); \
  40. meter.measure([&] { \
  41. is.clear(); \
  42. is.seekg(0, std::ios::beg); \
  43. return deSerializeJsonStringIfNeeded(is); \
  44. }); \
  45. };
  46. /* Both with and without a space character (' ') */
  47. #define BENCH2(_label, _chars, _length, _lengthlabel) \
  48. BENCH3(_label, _chars, _length, _lengthlabel) \
  49. BENCH3(_label "_with_space", " " _chars, _length, _lengthlabel) \
  50. /* Iterate over input lengths */
  51. #define BENCH1(_label, _chars) \
  52. BENCH2(_label, _chars, 10, "small") \
  53. BENCH2(_label, _chars, 10000, "large")
  54. /* Iterate over character sets */
  55. #define BENCH_ALL() \
  56. BENCH1("alpha", "abcdefghijklmnopqrstuvwxyz") \
  57. BENCH1("escaped", "\"\\/\b\f\n\r\t") \
  58. BENCH1("nonascii", "\xf0\xff")
  59. TEST_CASE("benchmark_serialize") {
  60. BENCH_ALL()
  61. }