title: Why does using fsync() to flush writes to disk speed up access?
body: <p>We need an app to as much as possible, guarantee that when it reports a record persisted, it really was. I understand that to do this you use <code>fsync(fd)</code>. However, for some strange reason, it appears using fsync() speeds up the code that writes to disk, instead of slowing it down as one would expect.</p>
  
  <p>Some sample test code returns the following results:</p>
  
  <pre><code>no sync() seconds:0.013388   writes per second:0.000001 
     sync() seconds:0.006268   writes per second:0.000002
  </code></pre>
  
  <p>Below is the code that produces these results:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;time.h&gt;
  #include &lt;unistd.h&gt;
  
  void withSync() {
      int f = open( "/tmp/t8" , O_RDWR | O_CREAT );
      lseek (f, 0, SEEK_SET );
      int records = 10*1000;
      clock_t ustart = clock();
      for(int i = 0; i &lt; records; i++) {
          write(f, "012345678901234567890123456789" , 30);
          fsync(f);
      }
      clock_t uend = clock();
      close (f);
      printf("   sync() seconds:%lf   writes per second:%lf\n", ((double)(uend-ustart))/(CLOCKS_PER_SEC), ((double)records)/((double)(uend-ustart))/(CLOCKS_PER_SEC));
  }
  
  void withoutSync() {
      int f = open( "/tmp/t10" , O_RDWR | O_CREAT );
      lseek (f, 0, SEEK_SET );
      int records = 10*1000;
      clock_t ustart = clock();
      for(int i = 0; i &lt; records; i++) {
          write(f, "012345678901234567890123456789" , 30 );
      }
      clock_t uend = clock();
      close (f);
      printf("no sync() seconds:%lf   writes per second:%lf \n", ((double)(uend-ustart))/(CLOCKS_PER_SEC), ((double)records)/((double)(uend-ustart))/(CLOCKS_PER_SEC));
  }
  
  int main(int argc, const char * argv[])
  {
      withoutSync();
      withSync();
      return 0;
  }
  </code></pre>