问题描述
线程SO采取,这块code来计算CPU周期数经过运行$ C行 // 1
和 // 2
。
Taken from this SO thread, this piece of code calculates the number of CPU cycles elapsed running code between lines //1
and //2
.
$ 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()
函数的工作?
推荐答案
函数执行x86指令RTDSC,这恰好有为0x0F,0X31 $ C $的运算code C>。处理器跟踪时钟周期的内部,而这个读取数。
The function executes the x86 instruction RTDSC, which happens to have an opcode of 0x0f, 0x31
. The processor keeps track of clock cycles internally, and this reads that number.
当然,这仅适用于x86的特效,其他处理器将需要不同的指令。
Of course, this only works on x86 procs, other processors will need different instructions.
时间戳计数器是自上奔腾的所有x86处理器在64位寄存器present。它计算自复位蜱的数量。指令RDTSC返回EDX的TSC:EAX。它的运算code是0F 31 [1]奔腾等竞争对手的Cyrix 6X86并不总是有TSC,可考虑RDTSC非法指令。 Cyrix的包括在他们MII一个时间戳计数器。
http://en.wikipedia.org/wiki/Time_Stamp_Counter
这篇关于请问这个code计算经过的CPU周期数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!