【问题标题】:rdtsc returns no resultsrdtsc 不返回任何结果
【发布时间】:2020-05-17 23:27:57
【问题描述】:

我正在尝试将 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

【问题讨论】:

  • 突出的两件事:第一,为什么在rdtsc指令之后清除结果寄存器eaxedx?其次,当你将左端的一个 32 位寄存器的所有 32 位移位时会发生什么?
  • 第一件事是复制错误。我的原始代码在 rdtsc 之前有那些。第二个是延迟,你是对的。

标签: assembly visual-c++ x86 masm rdtsc


【解决方案1】:

根据Wikipedia

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

【讨论】:

猜你喜欢
  • 2017-12-28
  • 2017-12-09
  • 2020-10-03
  • 2017-03-19
  • 2017-05-20
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多