title: fscanf vs ifstream speed
body: <p>I conjectured that <code>ifstream</code> would be faster than <code>fscanf</code> because <code>fscanf</code> has to parse the format string every time it runs, whereas, with <code>ifstream</code>, we know at compile time what kind of "thing" we want to read.</p>
  
  <p>But when I ran this quick and dirty benchmark</p>
  
  <pre><code>#include &lt;ctime&gt;
  #include &lt;cstdio&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  using namespace std;
  
  #define NUMBER_OF_NUMBERS 100000000
  
  int nums[NUMBER_OF_NUMBERS];
  
  int main(int argc, char** argv) {
  
      FILE * fp = fopen("nums.txt","r");
      auto start = clock();
      for (int i = 0; i &lt; NUMBER_OF_NUMBERS; i++)
          fscanf(fp,"%d",nums+i);
      auto end = clock();
      fclose(fp);
  
      auto first = end - start;
  
      ifstream fin("nums.txt");
      start = clock();
      for (int i = 0; i &lt; NUMBER_OF_NUMBERS; i++)
          fin &gt;&gt; nums[i];
      end = clock();
      fin.close();
  
      auto second = end - start;
  
      cout &lt;&lt; "CLOCKS_PER_SEC : " &lt;&lt; CLOCKS_PER_SEC &lt;&lt; endl;
      cout &lt;&lt; "first          : " &lt;&lt; first &lt;&lt; endl;
      cout &lt;&lt; "first (sec)    : " &lt;&lt; first / CLOCKS_PER_SEC &lt;&lt; " seconds" &lt;&lt; endl;
      cout &lt;&lt; "second         : " &lt;&lt; second &lt;&lt; endl;
      cout &lt;&lt; "second (sec)   : " &lt;&lt; second / CLOCKS_PER_SEC &lt;&lt; " seconds" &lt;&lt; endl;
      cout &lt;&lt; "diff           : " &lt;&lt; second - first &lt;&lt; endl;
      cout &lt;&lt; "diff (sec)     : " &lt;&lt; (second - first) / CLOCKS_PER_SEC &lt;&lt; " seconds" &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>I got as output the following:</p>
  
  <pre><code>CLOCKS_PER_SEC : 1000000
  first          : 12336249
  first (sec)    : 12 seconds
  second         : 25738587
  second (sec)   : 25 seconds
  diff           : 13402338
  diff (sec)     : 13 seconds
  </code></pre>
  
  <p><code>ifstream</code> is more than twice as slow as <code>fscanf</code>. Where does <code>fscanf</code> get all this speed?</p>
  
  <p>EDIT:</p>
  
  <p>I'm on a reasonably modern 64-bit intel mac, using command line tools that come with xcode, in case it is relevant at all.</p>