Performance Difference Between C and C++ Style File IO

前端 未结 3 811
萌比男神i
萌比男神i 2020-12-02 20:51

I\'ve always heard that C++ file I/O operations are much much slower then C style I/O. But I didn\'t find any practical references on comparatively how slow they actually ar

相关标签:
3条回答
  • 2020-12-02 21:17

    You're using endl to print a newline. That is the problem here, as it does more than just printing a newline — endl also flushes the buffer which is an expensive operation (if you do that in each iteration).

    Use \n if you mean so:

    file << i << '\n';
    

    And also, must compile your code in release mode (i.e turn on the optimizations).

    0 讨论(0)
  • 2020-12-02 21:19

    No, C++ input/output is not substantially slower than C’s – if anything, a modern implementation should be slightly faster on formatted input/output since it doesn’t need to parse a format string, and the formatting is instead determined at compile time through the chaining of the stream operators.

    Here are a few caveats to consider in a benchmark:

    • Compile with full optimisations (-O3) to get a fair comparison.
    • A proper benchmark needs to estimate biases – in practice this means that you need to repeat your tests and interleave them. At the moment your code isn’t robust to disturbances from background processes. You should also report a summary statistic of the repeated runs to catch outliers that distort the estimates.
    • Disable C++ stream synchronisation with C streams (std::ios_base::sync_with_stdio(false);)
    • Use '\n' instead of the (flushing) std::endl
    • Don’t use register declarations – it simply makes no difference and modern compilers probably ignore it anyway.
    0 讨论(0)
  • 2020-12-02 21:26

    When working with large files with fstream, make sure to set a stream buffer >0.

    Counterintuitively, disabling stream buffering dramatically reduces performance. At least the MSVC 2015 implementation copies 1 char at a time to the filebuf when no buffer was set (see streambuf::xsputn), which can make your application CPU-bound, which will result in lower I/O rates.

    const size_t bufsize = 256*1024;
    char buf[bufsize];
    mystream.rdbuf()->pubsetbuf(buf, bufsize);
    

    You can find a complete sample application here.

    0 讨论(0)
提交回复
热议问题