Why is buffering in C++ important?

前端 未结 5 1124
离开以前
离开以前 2021-01-30 12:00

I tried to print Hello World 200,000 times and it took me forever, so I have to stop. But right after I add a char array to act as a buffer, it took le

5条回答
  •  庸人自扰
    2021-01-30 12:03

    What compiler/platform are you using? I see no significant difference here (RedHat, gcc 4.1.2); both programs take 5-6 seconds to finish (but "user" time is about 150 ms). If I redirect output to a file (through the shell), total time is about 300 ms (so most of the 6 seconds is spent waiting for my console to catch up to the program).

    In other words, output should be buffered by default, so I'm curious why you're seeing such a huge speedup.

    3 tangentially-related notes:

    1. Your program has an off-by-one error in that you only print 199999 times instead of the stated 200000 (either start with i = 0 or end with i <= 200000)
    2. You're mixing printf syntax with cout syntax when outputting count...the fix for that is obvious enough.
    3. Disabling sync_with_stdio produces a small speedup (about 5%) for me when outputting to console, but the impact is negligible when redirecting to file. This is a micro-optimization which you probably wouldn't need in most cases (IMHO).

提交回复
热议问题