rdtsc指令返回的是自开机始CPU的周期数,返回的是一个64位的值EDX:EAX(高32在EDX,低32位在EAX)。OK,完全可以利用这条指令,测试我们的关注的一段代码的执行效率。
rdtsc直接通过汇编从寄存器中获取时间,时间消耗极低(0.0Xus左右的消耗,具体X为多少与机器本身相关)。精度可以精确到ns级别。
// 返回64位的CPU circle次数
inline unsigned long long getTimeByTSC(){
#if defined(__GNUC__)
# if defined(__i386__)
uint64_t x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
# elif defined(__x86_64__)
uint32_t hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)lo) | ((uint64_t)hi << 32);
# else
# error Unsupported architecture.
# endif
#elif defined(_MSC_VER)
__asm {
return __rdtsc();
}
#else
# error Other compilers not supported...
#endif
}