title: clock_gettime on Raspberry Pi with C
body: <p>I want to measure the time between the start to the end of the function in a loop. This difference will be used to set the amount of loops of the inner while-loops which does some here not important stuff.</p>
  
  <p>I want to time the function like this :</p>
  
  <pre><code>#include &lt;wiringPi.h&gt;
  #include &lt;time.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;unistd.h&gt;
  #define BILLION 1E9
  
  float hz = 1000;
  long int nsPerTick = BILLION/hz;
  
  double unprocessed = 1;
  struct timespec now;
  struct timespec last;
  clock_gettime(CLOCK_REALTIME, &amp;last);
  
  [ ... ]
  
  while (1) 
  {
      clock_gettime(CLOCK_REALTIME, &amp;now); 
  
      double diff = (last.tv_nsec - now.tv_nsec );
  
      unprocessed = unprocessed + (diff/ nsPerTick);
      clock_gettime(CLOCK_REALTIME, &amp;last);
  
  
      while (unprocessed &gt;= 1) { 
              unprocessed --;
              DO SOME RANDOM MAGIC;
              }
      }
  </code></pre>
  
  <p>The difference between the timer is always negative. I was told this was where the error was:</p>
  
  <pre><code>    if ( (last.tv_nsec - now.tv_nsec)&lt;0) {
           double diff = 1000000000+ last.tv_nsec - now.tv_nsec;
           }
      else {
           double diff = (last.tv_nsec - now.tv_nsec );
      }
  </code></pre>
  
  <p>But still, my variable difference and is always negative like "-1095043244" (but the time spent during the function is a positive of course).</p>
  
  <p>What's wrong?</p>