title: Measuring time difference using RDTSC - results too large
body: <p>I'm  trying to calculate number of CPU cycles required to run single ASM instruction. In order to do this, I've created this function:</p>
  
  <pre><code>measure_register_op:
      # Calculate time of required for movl operation
  
      # function setup
      pushl %ebp
      movl %esp, %ebp
      pushl %ebx
      pushl %edi
  
      xor %edi, %edi
  
      # first time measurement
      xorl %eax, %eax
      cpuid               # sync of threads
      rdtsc               # result in edx:eax
  
      # we are measuring instuction below
      movl %eax, %edi     
  
      # second time measurement
      cpuid               # sync of threads
      rdtsc               # result in edx:eax
  
      # time difference
      sub %eax, %edi
  
      # move to EAX. Value of EAX is what function returns
      movl %edi, %eax
  
      # End of function
      popl %edi
      popl %ebx
      mov %ebp, %esp
      popl %ebp
  
      ret
  </code></pre>
  
  <p>I'm using it in *.c file:</p>
  
  <pre><code>extern unsigned int measure_register_op();
  
  int main(void)
  {
  
      for (int a = 0; a &lt; 10; a++)
      {
          printf("Instruction took %u cycles \n", measure_register_op());
      }
  
      return 0;
  }
  </code></pre>
  
  <p>The problem is: the values I see are way too large. I'm getting <code>3684414156</code> now. What could go wrong here?</p>
  
  <p>EDIT:
  Changed from EBX to EDI, but result is still similar. It have to be something with rdtsc itself. In debugger I can see that second measurement results with 0x7f61e078 and first 0x42999940, which, after substraction still gives around <code>1019758392</code></p>
  
  <p>EDIT:
  Here is my makefile. Maybe I'm compiling it incorrectly:</p>
  
  <pre><code>compile: measurement.s measurement.c
      gcc -g measurement.s measurement.c -o ./build/measurement -m32
  </code></pre>
  
  <p>EDIT:
  Here is an exact result I see:</p>
  
  <pre><code>Instruction took 4294966680 cycles 
  Instruction took 4294966696 cycles 
  Instruction took 4294966688 cycles 
  Instruction took 4294966672 cycles 
  Instruction took 4294966680 cycles 
  Instruction took 4294966688 cycles 
  Instruction took 4294966688 cycles 
  Instruction took 4294966696 cycles 
  Instruction took 4294966688 cycles 
  Instruction took 4294966680 cycles 
  </code></pre>