How To Get The Current CPU Cycle Count

December 18, 2008

With a little bit of help from assembler, we can find the exact CPU cycle count. This can be very much helpful to find the execution time of a program or function. The code to find the cpu cycle count is given below.

 
__int64 GetCpuCycle()
{
   unsigned int LowWord = 0;
   unsigned int HighWord = 0;
   _asm
   {
      // Insert Real Time Stamp Counter opcodes
      _emit 0x0F
      _emit 0x31
      mov HighWord, edx
      mov LowWord, eax
   }
   return ((__int64)(HighWord) << 32) + LowWord;
}

We can use the above function at the beginning and end of a program to get the no. of clock cycles it needed.