Printing to the console vs writing to a file (speed)

后端 未结 4 989
执笔经年
执笔经年 2020-12-16 13:36

In C++, which would be faster if repeated, say, 5000 times:

cout << \"text!\" << endl;

or

my_text_file <<         


        
4条回答
  •  不思量自难忘°
    2020-12-16 14:07

    In addition to console I/O generally being relatively slow, the default configuration of the standard streams cout and cin has some issues that will greatly slow performance if not corrected.

    The reason is that the standard mandates that, by default, cout and cin from the C++ iostream library should work alongside stdout and stdin from the C stdio library in the expected way.

    This basically means that cout and cin can't do any buffering at all in its internal streambufs and basically forwards all I/O operations over to the C library.

    If you want to do anything resembling high performance I/O with the standard streams, you need to turn off this synchronization with

    std::ios_base::sync_with_stdio(false);
    

    before doing any I/O.

提交回复
热议问题