title: Negative clock cycle measurements with back-to-back rdtsc?
body: <p>I am writing a C code for measuring the number of clock cycles needed to acquire a semaphore. I am using rdtsc, and before doing the measurement on the semaphore, I call rdtsc two consecutive times, to measure the overhead. I repeat this many times, in a for-loop, and then I use the average value as rdtsc overhead.</p>
  
  <p>Is this correct, to use the average value, first of all?</p>
  
  <p>Nonetheless, the big problem here is that sometimes I get negative values for the overhead (not necessarily the averaged one,but at least the partial ones inside the for loop).</p>
  
  <p>This also affects the consecutive calculation of the number of cpu cycles needed for the <code>sem_wait()</code> operation, which sometimes also turns out to be negative. If what I wrote is not clear, here there's a part of the code I am working on.</p>
  
  <p>Why am I getting such negative values?</p>
  
  <hr>
  
  <p>(editor's note: see <a href="https://stackoverflow.com/questions/13772567/get-cpu-cycle-count">Get CPU cycle count?</a> for a correct and portable way of getting the full 64-bit timestamp.  An <code>"=A"</code> asm constraint will only get the low or high 32 bits when compiled for x86-64, depending on whether register allocation happens to pick RAX or RDX for the <code>uint64_t</code> output.  It won't pick <code>edx:eax</code>.)</p>
  
  <p>(editor's 2nd note: oops, that's the answer to why we're getting negative results.  Still worth leaving a note here as a warning not to copy this <code>rdtsc</code> implementation.)</p>
  
  <hr>
  
  <pre><code>#include &lt;semaphore.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;inttypes.h&gt;
  
  static inline uint64_t get_cycles()
  {
    uint64_t t;
             // editor's note: "=A" is unsafe for this in x86-64
    __asm volatile ("rdtsc" : "=A"(t));
    return t;
  }
  
  int num_measures = 10;
  
  int main ()
  {
     int i, value, res1, res2;
     uint64_t c1, c2;
     int tsccost, tot, a;
  
     tot=0;    
  
     for(i=0; i&lt;num_measures; i++)
     {    
        c1 = get_cycles();
        c2 = get_cycles();
  
        tsccost=(int)(c2-c1);
  
  
        if(tsccost&lt;0)
        {
           printf("####  ERROR!!!   ");
           printf("rdtsc took %d clock cycles\n", tsccost);
           return 1;
        }   
        tot = tot+tsccost;
     }
  
     tsccost=tot/num_measures;
     printf("rdtsc takes on average: %d clock cycles\n", tsccost);      
  
     return EXIT_SUCCESS;
  }
  </code></pre>