Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Believe it or not, the performance of the stdlib stream in reading data is far below that of the C library routines. If you need top IO read performance, don't use c++ streams. I discovered this the hard way on algorithm competition sites -- my code would hit the test timeout using c++ streams to read stdin, but would finish in plenty of time using plain C FILE operations.</p> <p>Edit: Just try out these two programs on some sample data. I ran them on Mac OS X 10.6.6 using g++ i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664) on a file with 1 million lines of "howdythere", and the scanf version runs consistently 5 times faster than the cin version:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int count = 0; char buf[1024]; while ( scanf("%s", buf) == 1 ) ++ count; printf( "%d lines\n", count ); } </code></pre> <p>and</p> <pre><code>#include &lt;iostream&gt; int main() { char buf[1024]; int count = 0; while ( ! std::cin.eof() ) { std::cin.getline( buf, 1023 ); if ( ! std::cin.eof() ) ++count; } std::cout &lt;&lt; count &lt;&lt; " lines" &lt;&lt; std::endl; } </code></pre> <p>Edit: changed the data file to "howdythere" to eliminate the difference between the two cases. The timing results did not change.</p> <p>Edit: I think the amount of interest (and the downvotes) in this answer shows how contrary to popular opinion the reality is. People just can't believe that the simple case of reading input in both C and streams can be so different. Before you downvote: go measure it yourself. The point is not to set tons of state (that nobody typically sets), but just the code that people most frequently write. Opinion means nothing in performance: measure, measure, measure is all that matters.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload