|
| 1 | +// Standard: C++23 |
| 2 | +// std::print vs cout(sync 开/关) vs printf 的格式化性能对比 |
| 3 | +// 200 万条短行写到 /dev/null(排除终端 I/O 噪声,只测格式化与缓冲), |
| 4 | +// 耗时打到 stderr——print 绕开 cout 的虚调用 + sync 开销,通常最快。 |
| 5 | +#include <chrono> |
| 6 | +#include <cstdio> |
| 7 | +#include <iostream> |
| 8 | +#include <print> |
| 9 | + |
| 10 | +constexpr int kIterations = 2'000'000; |
| 11 | + |
| 12 | +static void report(const char* name, std::chrono::steady_clock::time_point t0, |
| 13 | + std::chrono::steady_clock::time_point t1) { |
| 14 | + auto us = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count(); |
| 15 | + std::fprintf(stderr, "%-22s %lld us\n", name, (long long)us); |
| 16 | +} |
| 17 | + |
| 18 | +void bench_cout_sync() { |
| 19 | + std::ios::sync_with_stdio(true); // 默认 |
| 20 | + auto t0 = std::chrono::steady_clock::now(); |
| 21 | + for (int i = 0; i < kIterations; ++i) { |
| 22 | + std::cout << "i=" << i << " sq=" << i * 2 << '\n'; |
| 23 | + } |
| 24 | + report("cout (sync=true)", t0, std::chrono::steady_clock::now()); |
| 25 | +} |
| 26 | + |
| 27 | +void bench_cout_nosync() { |
| 28 | + std::ios::sync_with_stdio(false); // 常见的"加速 cout"写法 |
| 29 | + auto t0 = std::chrono::steady_clock::now(); |
| 30 | + for (int i = 0; i < kIterations; ++i) { |
| 31 | + std::cout << "i=" << i << " sq=" << i * 2 << '\n'; |
| 32 | + } |
| 33 | + report("cout (sync=false)", t0, std::chrono::steady_clock::now()); |
| 34 | +} |
| 35 | + |
| 36 | +void bench_printf() { |
| 37 | + auto t0 = std::chrono::steady_clock::now(); |
| 38 | + for (int i = 0; i < kIterations; ++i) { |
| 39 | + std::printf("i=%d sq=%d\n", i, i * 2); |
| 40 | + } |
| 41 | + report("printf", t0, std::chrono::steady_clock::now()); |
| 42 | +} |
| 43 | + |
| 44 | +void bench_print() { |
| 45 | + auto t0 = std::chrono::steady_clock::now(); |
| 46 | + for (int i = 0; i < kIterations; ++i) { |
| 47 | + std::print("i={} sq={}\n", i, i * 2); |
| 48 | + } |
| 49 | + report("print", t0, std::chrono::steady_clock::now()); |
| 50 | +} |
| 51 | + |
| 52 | +int main() { |
| 53 | + std::freopen("/dev/null", "w", stdout); // 排除终端 I/O 噪声 |
| 54 | + bench_cout_sync(); |
| 55 | + bench_printf(); |
| 56 | + bench_print(); |
| 57 | + bench_cout_nosync(); |
| 58 | + return 0; |
| 59 | +} |
0 commit comments