c++ - 如何将此程序集时间戳函数转换为 C++?

标签 c++ inline-assembly rdtsc

<分区>

我正在尝试将其他人的项目从 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;\n\t"
        "movl %%eax, %0;\n\t"
        "movl %%edx, %1;" 
        :"=r"(tmp1),"=r"(tmp2)
        :
        :
        );
#endif

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

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

最佳答案

对于 Windows 分支,

#include <intrin.h>

并调用 __rdtsc() 内部函数。

文档 on MSDN

对于 Linux 分支,内部函数以相同的名称提供,但您需要不同的头文件:

#include <x86intrin.h>

关于c++ - 如何将此程序集时间戳函数转换为 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32655678/

相关文章:

linux - 跨 CPU 内核的 rdtsc 精度

optimization - NASM中的RDTSCP始终返回相同的值

c++ - 使用qml + QQuickView作为初始屏幕不起作用

c++指针操作等同于ReadProcessMemory

c++ - RDTSCP 和指令顺序

x86 - 如何保证RDTSC是准确的?

c++ - 使用 Paho MQTT C++ 连接到 AdafruitIO

c++ - 以 24 小时格式表示的两次时间之间耗时 hh :mm:ss

gcc - 为什么这个带有 gcc (clang) 内联汇编的简单 c 程序表现出未定义的行为?

c++ - 如何使用函数指针从其内存地址调用成员函数?