title: time() and gettimeofday() return different seconds
body: <p>On the two systems I've tested (a 32-bit Ubuntu 12.04 server and a 64-bit Ubuntu 13.10 VM), the seconds since the epoch given by <a href="http://linux.die.net/man/2/time" rel="noreferrer">time()</a> may differ from <a href="http://linux.die.net/man/2/gettimeofday" rel="noreferrer">gettimeofday()</a>'s.</p>
  
  <p>Specifically, though I call <code>time()</code> <em>after</em> calling <code>gettimeofday()</code>, the value returned by <code>time()</code> is sometimes <em>less than</em> the <code>tv_sec</code> value returned by <code>gettimeofday()</code>.</p>
  
  <p>This apparently occurs just after the clock rolls over to a new second.</p>
  
  <p>This caused bugs in some of my code that expected time()'s and gettimeofday()'s seconds to be interchangeable.</p>
  
  <p>Sample code demonstrating this problem:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;time.h&gt;
  #include &lt;sys/time.h&gt;
  
  int main()
  {
    time_t start = time(NULL);
    int same = 0;
    int different = 0;
    int max_usec = 0;
    while (1) {
      time_t t;
      struct timeval tv;
      gettimeofday(&amp;tv, NULL);
      t = time(NULL);
      if (t &lt; tv.tv_sec) {
        different++;
        if (tv.tv_usec &gt; max_usec) {
          max_usec = tv.tv_usec;
        }
      } else {
        same++;
      }
      if (t &gt; start + 5) {
        break;
      }
    }
    printf("Same:      %i\n", same);
    printf("Different: %i\n", different);
    printf("Largest difference seen at %i\n", max_usec);
  }
  </code></pre>
  
  <p>Note that I'm calling time() second and only complaining if its value is <em>less</em> than gettimeofday()'s.</p>
  
  <p>Sample output:</p>
  
  <pre><code>Same:      33282836
  Different: 177076
  Largest difference seen at 5844
  </code></pre>
  
  <p>I.e., the two values were the same 33 million times, they were different 177k times, and they were always different within 5844 microseconds of a new second.</p>
  
  <p>Is this a known issue?  What causes this?</p>