rdtsc returns 没有结果

rdtsc returns no results

我正在尝试将 rdtsc 用作计时器,但 eax 和 edx 寄存器要么保持为空,要么形成的数字与 MS 的 __rdtsc 函数给出的数字非常不同 instrin.h图书馆。

这里是汇编代码:

.model flat, c

.code

get_curr_cycle proc
cpuid
cpuid
cpuid
xor eax, eax ; empty eax register
xor edx, edx ; empty edx register
rdtsc
shl edx, 32 ; shift high bits to the left
or edx, eax ; or the high bits to the low bits
mov eax, edx ; move the final result into eax
retn
get_curr_cycle endp

end

这里是 C++ 代码:

#include <iostream>
#include <intrin.h>

extern "C" long long get_curr_cycle();

int main()
{
    long long t1 = __rdtsc();
    long long t2 = get_curr_cycle();

    for(unsigned int i = 0; i <= 10; ++i)
    {
        printf("%d - %d\n", t1, t2);
    }

    getchar();

    return 0;
}

这是我最后的输出:

87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162

根据Wikipedia

The instruction RDTSC returns the TSC in EDX:EAX. In x86-64 mode, RDTSC also clears the higher 32 bits of RAX and RDX.

因此,在 x86 上,您的代码可以简单地为:

get_curr_cycle proc
rdtsc
retn
get_curr_cycle endp

return edx:eax 中的当前计时器值。

在 x64 上,您可以:

get_curr_cycle proc
rdtsc
shl rdx, 32
or rax, rdx
retn
get_curr_cycle endp

这将 return rax 中的计时器值。

另外,printf 的格式说明符是错误的。他们应该是 %lld.