You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含rdtsc的x86汇编转C++:mov esi,dest的等价实现解析

问题解答

1. 解释mov esi, dest的含义

dest是指向unsigned __int64变量high_perf_time的指针,mov esi, dest的作用是把dest中存储的内存地址(也就是high_perf_time的地址)加载到ESI寄存器中。

后续的两条mov指令配合完成TSC值的存储:

  • mov [esi], eax:将RDTSC指令存在EAX里的TSC低32位值,写入ESI指向的内存(即high_perf_time的低4字节)
  • mov [esi+4], edx:将RDTSC存在EDX里的TSC高32位值,写入ESI地址偏移4字节的位置(即high_perf_time的高4字节)

这三步合起来,就是把RDTSC读取到的64位时间戳计数器(TSC)值,完整存入high_perf_time变量中。

2. 纯C++实现方案

不需要依赖内嵌汇编,直接用编译器提供的内置函数就能实现相同逻辑,兼容性更好:

针对MSVC编译器

#include <cstdint>

uint64_t high_perf_time = __rdtsc(); // __rdtsc()直接返回64位TSC值

int64_t time_s     = static_cast<int64_t>(high_perf_time / frequency);
int64_t time_fract = static_cast<int64_t>(high_perf_time % frequency);

针对GCC/Clang编译器

#include <cstdint>

uint64_t high_perf_time = __rdtsc(); // 同样支持__rdtsc()内置函数

int64_t time_s     = static_cast<int64_t>(high_perf_time / frequency);
int64_t time_fract = static_cast<int64_t>(high_perf_time % frequency);

跨编译器兼容写法(可选)

通过宏判断编译器类型,统一调用逻辑:

#include <cstdint>

#ifdef _MSC_VER
#define RDTSC() __rdtsc()
#elif defined(__GNUC__) || defined(__clang__)
#define RDTSC() __rdtsc()
#endif

uint64_t high_perf_time = RDTSC();

int64_t time_s     = static_cast<int64_t>(high_perf_time / frequency);
int64_t time_fract = static_cast<int64_t>(high_perf_time % frequency);

注:如果需要避免CPU乱序执行的影响,可以使用带序列化的__rdtscp(),但它需要额外处理CPUID相关的寄存器输出。

内容的提问来源于stack exchange,提问作者maor03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:15:05