Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As Slava says, streams (i.e cin) are absolute pigs in terms of performance (and executable file size)</p> <p>Consider the following two approaches:</p> <pre><code>start = clock(); std::ios_base::sync_with_stdio (false); // Supposedly makes I/O faster cin &gt;&gt; NumberOfCities &gt;&gt; NumberOfOldRoads; Roads = new Road[NumberOfOldRoads]; for (int i = 0; i &lt; NumberOfOldRoads; i++) { int cityA, cityB, length; cin &gt;&gt; cityA &gt;&gt; cityB &gt;&gt; length; Roads[i] = Road(cityA, cityB, length); } stop = clock(); printf ("time: %d\n", stop-start); </code></pre> <p>and</p> <pre><code>start = clock(); fp = stdin; fscanf(fp, "%d\n%d\n", &amp;NumberOfCities, &amp;NumberOfOldRoads); Roads = new Road[NumberOfOldRoads]; for (int i = 0; i &lt; NumberOfOldRoads; i++) { int cityA, cityB, length; fscanf(fp, "%d %d %d\n", &amp;cityA, &amp;cityB, &amp;length); Roads[i] = Road(cityA, cityB, length); } stop = clock(); printf ("time: %d\n", stop-start); </code></pre> <p>Running each way 5 times (with an input file of 1,000,000 entries + the first 2 'control' lines) gives us these results:</p> <ol> <li><p>Using cin <strong><em>without</em></strong> the direction to not sync with stdio 8291, 8501, 8720, 8918, 7164 (avg 8318.3)</p></li> <li><p>Using cin <strong><em>with</em></strong> the direction to not sync with stdio 4875, 4674, 4921, 4782, 5171 (avg 4884.6)</p></li> <li><p>Using fscanf 1681, 1676, 1536, 1644, 1675 (avg 1642.4)</p></li> </ol> <p>So, clearly, one can see that the sync_with_stdio(false) direction does help. One can also see that fscanf beats the pants off each approach with cin. In fact, the fscanf approach is nearly <strong><em>3 times faster</em></strong> than the better of the cin approaches and a whopping <strong><em>5 times faster</em></strong> than cin when not told to avoid syncing with stdio.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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