Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function __asm__ __volatile__("rdtsc");

Tags:

c++

x86

rdtsc

I don't know what exactly does this code:

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

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

like image 742
user17629 Avatar asked Oct 20 '25 16:10

user17629


1 Answers

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

like image 102
Mats Petersson Avatar answered Oct 23 '25 04:10

Mats Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!