assembly - 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
解决方案
根据维基百科:
指令 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
。
推荐阅读
- r - dplyr 的 sample_frac 函数返回错误
- microsoft-graph-api - MS Graph API 团队:获取消息计数
- scip - SCIP:在特定节点以各种模式获取下限和上限
- swift - 如何在collectionview中查看pdf文件?
- python - Python selenium 一直等待整个页面加载,即使有显式等待
- c - 无法将结构指针传递给 C 中函数内的函数
- swift - 将承载令牌添加到 Swift 中的标头的问题(HTTP POST 调用)
- gatsby - Gatsby、RSS 提要和无头 CMS
- javascript - “下载”图像并添加到数组
- r - 从数据框中的列中采样唯一行而不进行替换