如何将这个汇编时间戳函数转换为c++

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

本文关键字:函数 转换 c++ 时间戳 汇编      更新时间:2023-10-16

我正试图将别人的项目从32位转换为64位。一切似乎都很好,除了一个函数,它使用汇编表达式,在构建x64时不支持Visual Studio:

// 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;nt"
        "movl %%eax, %0;nt"
        "movl %%edx, %1;" 
        :"=r"(tmp1),"=r"(tmp2)
        :
        :
        );
#endif
    return ((int64_t)tmp1 * (int64_t)tmp2);
}

最有趣的是,它被用来生成随机数。asm块都不能在x64下编译,所以玩弄ifdef是没有帮助的。我只需要找到C/c++的替代品,以避免重写整个程序。

对于Windows分支,

#include <intrin.h>

,调用__rdtsc()内禀函数

MSDN文档

对于Linux分支,内部文件在相同的名称下可用,但您需要一个不同的头文件:

#include <x86intrin.h>