Search code examples
c++inline-assemblyrdtsc

How can I convert this assembly timestamp function to C++?


I am trying to convert someone else's project from 32bit to 64bit. Everything seems to be OK except one function, which uses assembly expressions which are not supported in Visual Studio when building x64:

// Returns the Read Time Stamp Counter of the CPU
// The instruction returns in registers EDX:EAX the count of ticks from processor reset.
// Added in Pentium. Opcode: 0F 31.
int64_t CDiffieHellman::GetRTSC( void )
{
    int tmp1 = 0;
    int tmp2 = 0;

#if defined(WIN32)
    __asm
    {
        RDTSC;          // Clock cycles since CPU started
        mov tmp1, eax;
        mov tmp2, edx;
    }
#else
    asm( "RDTSC;\n\t"
        "movl %%eax, %0;\n\t"
        "movl %%edx, %1;" 
        :"=r"(tmp1),"=r"(tmp2)
        :
        :
        );
#endif

    return ((int64_t)tmp1 * (int64_t)tmp2);
}

Most funny thing about this is, that this is being used for generating random numbers. Neither asm block compiles under x64, so playing with ifdef doesn't help. I just need to find C/C++ replacement to avoid rewriting whole program.


Solution

  • For the Windows branch,

    #include <intrin.h>
    

    and call the __rdtsc() intrinsic function.

    Documentation on MSDN

    For the Linux branch, the intrinsic is available under the same name, but you need a different header file:

    #include <x86intrin.h>