从
this SO thread开始,该代码计算行// 1和// 2之间运行代码的cpu周期数.
$cat cyc.c #include<stdio.h> static __inline__ unsigned long long rdtsc(void) { unsigned long long int x; __asm__ volatile (".byte 0x0f,0x31" : "=A" (x)); return x; } int main() { unsigned long long cycles = rdtsc(); //1 cycles = rdtsc() - cycles; //2 printf("Time is %d\n",(unsigned)cycles); return 0; } $gcc cyc.c -o cyc $./cyc Time is 73 $./cyc Time is 74 $./cyc Time is 63 $./cyc Time is 73 $
rdtsc()函数如何工作?
解决方法@H_403_8@
该函数执行x86指令RTDSC,它的操作码为0x0f,0x31.处理器内部跟踪时钟周期,并读取该数字.
当然,这只适用于x86 procs,其他处理器将需要不同的指令.
The Time Stamp Counter is a 64-bit register present on all x86 processors since the Pentium. It counts the number of ticks since reset. Instruction RDTSC returns the TSC in EDX:EAX. Its opcode is 0F 31.[1] Pentium competitors such as the Cyrix 6×86 did not always have a TSC and may consider RDTSC an illegal instruction. Cyrix included a Time Stamp Counter in their MII.
当然,这只适用于x86 procs,其他处理器将需要不同的指令.
The Time Stamp Counter is a 64-bit register present on all x86 processors since the Pentium. It counts the number of ticks since reset. Instruction RDTSC returns the TSC in EDX:EAX. Its opcode is 0F 31.[1] Pentium competitors such as the Cyrix 6×86 did not always have a TSC and may consider RDTSC an illegal instruction. Cyrix included a Time Stamp Counter in their MII.