这段代码如何计算经过的 CPU 周期数?

发布于 2024-09-26 19:00:54 字数 637 浏览 3 评论 0原文

这段代码取自这个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离鸿 2024-10-03 19:00:54

该函数执行 x86 指令 RTDSC,该指令的操作码恰好为 0x0f, 0x31。处理器在内部跟踪时钟周期,并读取该数字。

当然,这仅适用于 x86 处理器,其他处理器将需要不同的指令。

时间戳计数器是自 Pentium 以来所有 x86 处理器上都存在的 64 位寄存器。它计算自重置以来的滴答数。指令 RDTSC 返回 EDX:EAX 中的 TSC。它的操作码是0F 31。[1] Pentium 竞争对手(例如 Cyrix 6x86)并不总是有 TSC,并且可能认为 RDTSC 是非法指令。 Cyrix 在其 MII 中包含了一个时间戳计数器。

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.

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 6x86 did not always have a TSC and may consider RDTSC an illegal instruction. Cyrix included a Time Stamp Counter in their MII.

http://en.wikipedia.org/wiki/Time_Stamp_Counter

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文