这段代码如何计算经过的 CPU 周期数?
这段代码取自这个SO线程,计算行之间运行代码所消耗的CPU周期数// 1
和 //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() 函数如何工作?
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
$
How does the rdtsc()
function work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该函数执行 x86 指令 RTDSC,该指令的操作码恰好为
0x0f, 0x31
。处理器在内部跟踪时钟周期,并读取该数字。当然,这仅适用于 x86 处理器,其他处理器将需要不同的指令。
http://en.wikipedia.org/wiki/Time_Stamp_Counter
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.Of course, this only works on x86 procs, other processors will need different instructions.
http://en.wikipedia.org/wiki/Time_Stamp_Counter