Function __asm__ __volatile__(“rdtsc”);

天涯浪子 提交于 2019-12-23 06:37:05

问题


I don't know what exactly does this code:

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

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


回答1:


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

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

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.

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 );
}

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.

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?.




回答2:


The often-cited inline assembly for rdtsc produces supeflous code with gcc-7 and earlier versions.

A more efficient solution is to use __builtin_ia32_rdtsc built-in function:

uint64_t tsc = __builtin_ia32_rdtsc();


来源:https://stackoverflow.com/questions/23402701/function-asm-volatile-rdtsc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!