Micro-benchmark for https://github.com/p-ranav/tabulate/issues/74: is std::format a faster way to build the padded/repeated strings the printer writes (cell alignment padding, repeated border characters), compared to the std::string concatenation tabulate currently uses?
| 222 | // writes (cell alignment padding, repeated border characters), compared to |
| 223 | // the std::string concatenation tabulate currently uses? |
| 224 | void benchmark_padding_construction(Table &results) { |
| 225 | const int iterations = 200000; |
| 226 | const size_t width = 24; |
| 227 | volatile size_t sink = 0; // prevents the optimizer from eliding the loop body |
| 228 | |
| 229 | double concat_ms = time_ms([&] { |
| 230 | for (int i = 0; i < iterations; ++i) { |
| 231 | std::string padded = std::string(width - 2, ' ') + "hi"; |
| 232 | sink += padded.size(); |
| 233 | } |
| 234 | }); |
| 235 | results.add_row(Row_t{"std::string concatenation (current)", ms_str(concat_ms)}); |
| 236 | |
| 237 | #if defined(TABULATE_BENCHMARK_HAS_STD_FORMAT) |
| 238 | double format_ms = time_ms([&] { |
| 239 | for (int i = 0; i < iterations; ++i) { |
| 240 | std::string padded = std::format("{:>{}}", "hi", width); |
| 241 | sink += padded.size(); |
| 242 | } |
| 243 | }); |
| 244 | results.add_row(Row_t{"std::format (C++20)", ms_str(format_ms)}); |
| 245 | #else |
| 246 | results.add_row(Row_t{"std::format (C++20)", "not available (compiled with < C++20)"}); |
| 247 | #endif |
| 248 | (void)sink; |
| 249 | } |
| 250 | |
| 251 | // Builds a rows x cols table where every cell holds a long sentence that |
| 252 | // won't fit on one line at any reasonably narrow column width, used by the |