函数 __asm__ __volatile__(“rdtsc"); [英] Function __asm__ __volatile__("rdtsc");

查看:145
本文介绍了函数 __asm__ __volatile__(“rdtsc");的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这段代码到底是做什么的:

I don't know what exactly does this code:

int rdtsc(){
    __asm__ __volatile__("rdtsc");

拜托,有人能解释一下吗?为什么是rdtsc"?

Please, someone can explain me? why "rdtsc"?

推荐答案

实际上,这根本不是很好的代码.

Actually, that's not very good code at all.

RDTSC 是 x86 指令读取时间戳计数器" - 它读取一个 64 位计数器,该计数器在处理器的每个时钟周期计数.

RDTSC is the x86 instruction "ReaD TimeStamp Counter" - it reads a 64-bit counter that counts up at every clock cycle of your processor.

但由于它是一个 64 位数字,所以它存储在 EAX(低部分)和 EDX(高部分)中,如果此代码曾经用于内联的情况下,编译器不知道 EDX 正在被破坏.或者内联汇编在脱离非 void 函数的末尾之前设置 EAX.

But since it's a 64-bit number, it's stored in EAX (low part) and EDX (high part), and if this code is ever used in a case where it is inlined, the compiler doesn't know that EDX is being clobbered. Or that the inline assembly sets EAX before falling off the end of a non-void function.

编译器不理解"汇编代码,它是一个黑匣子,您必须用输入/输出操作数对其进行描述,以便它知道EDX:EAX 中有一个输出.(或者 EAX 中的输出,EDX 被破坏了).我会这样做:

The compiler doesn't "understand" the assembler code, it's a black box which you must describe with input/output operands so it knows there's an output in EDX:EAX. (Or an output in EAX with EDX being clobbered). I would do this:

uint64_t rdtsc()
{
   uint32_t hi, lo;
   __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
   return ( (uint64_t)lo)|( ((uint64_t)hi)<<32 );
}

因此给出的时间计数不会在现代机器上每秒或每两秒回绕一次,并告诉编译器注册您的 asm 语句修改.

thus giving a time-count that doesn't wrap around every second or two on a modern machine, and which tells the compiler which registers your asm statement modifies.

或者使用 __rdtsc() 内在函数让编译器自己发出 rdtsc 指令,并知道输出在哪里.请参阅获取 CPU 周期计数?.

Or use the __rdtsc() intrinsic to get the compiler to emit the rdtsc instruction itself, and know where the outputs are. See Get CPU cycle count?.

这篇关于函数 __asm__ __volatile__(“rdtsc");的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆