title: Monotonic Clock in C
body: <p>I'm doing a algorithm project for my University. In the project I have to write some algorithms and evaluate their time using a <strong>monotonic</strong> clock.</p>
  <p>I've already implemented everything using C but now I'm facing problems with the time measuring.</p>
  <p>I'm currently using <code>clock_gettime(CLOCK_MONOTONIC_RAW, ...)</code> to get a clock. From the manpage of <code>clock_gettime</code>:</p>
  <pre><code>CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)
                Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments
                or  the  incremental  adjustments  performed by adjtime(3).  This clock does not count time that the system is sus‐
                pended.
  </code></pre>
  <p>The problem is the following: this clock <em>sometimes</em> returns a negative value when a measure like this is done:</p>
  <pre><code>struct timespec start,end;
  
  clock_gettime(CLOCK_MONOTONIC_RAW, &amp;start);
  do{
      // do stuff in here
      clock_gettime(CLOCK_MONOTONIC_RAW, &amp;end);
  } while((double) (end.tv_nsec - start.tv_nsec) &lt;= *a certain quantity needed for precision*);
  </code></pre>
  <p>In particular, sometimes <code>end.tv_nsec - start.tv_nsec</code> is negative and this causes the program to loop into this do-while.</p>
  <p>As this <em><strong>should</strong></em> be a monotonic clock (which never goes back), things like having a negative elapsed time should not happen. But still, it seems to be happening.</p>
  <p>Is this clock really monotonic? Am i doing something wrong? What can I try to figure out what is wrong?</p>
  <p>I am really lost, I've tried lot of things in the past few days and none has worked out.
  In the case that more code is needed, see my repo: <a href="https://github.com/AlessandroZanatta/AlgorithmsProject/blob/dev/first_part/times.c" rel="nofollow noreferrer">https://github.com/AlessandroZanatta/AlgorithmsProject/blob/dev/first_part/times.c</a></p>