Programming Tips & Tricks

Home Categories: C# | C++ | General | Other

C++ Tips & Tricks: RDTSC Cycle Counting

The RDTSC instruction allows you to get the cpu's current cycle count. With this it's easy to write code to measure how many cycles some function needs.
But bear in mind that you can never get an exact count of how many cycles some function actually uses, since the operating system and other programs running in the background will consume cycles too.
You might also be more comfortable with using some OS or API specific way to measure time/cycles, like the Win32 QueryPerformanceCounter :)
But here is the code to get the current cycle count, using inline assembly to access the rdtsc instruction:
__int64 GetCPUCount ( unsigned int loword, unsigned int hiword )
_emit 0x0f // insert rtdsc opcode
_emit 0x31
mov hiword , edx
mov loword , eax
return ( (__int64) hiword << 32 ) + loword;

Here is how you would use it to measure the amount of cycles needed by MyFunction():
unsigned int hi = 0, lo = 0; 
double t = GetCPUCount ( lo, hi );

MyFunction ();

double CycleCount = GetCPUCount ( lo, hi ) - t;

Related Tips: CPUID and RDTSC