首页 > 解决方案 > rdtsc 不返回任何结果

问题描述

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

这是汇编代码:

.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

标签: assemblyvisual-c++x86masmrdtsc

解决方案


根据维基百科

指令 RDTSC 返回 EDX:EAX 中的 TSC。在 x86-64 模式下,RDTSC 还会清除 RAX 和 RDX 的高 32 位。

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

get_curr_cycle proc
rdtsc
retn
get_curr_cycle endp

它将返回当前计时器值edx:eax

在 x64 上,您可以执行以下操作:

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

这将返回中的计时器值rax

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


推荐阅读