rdtsc()给出了奇怪的结果

时间:2013-08-19 01:35:10

标签: c linux optimization rdtsc

我写了一个非常简单的C程序,试图理解C(Linux)中的rdtsc。程序如下:

#include <stdio.h>

static inline unsigned long long tick()
{
        unsigned long long d;
        __asm__ __volatile__ ("rdtsc" : "=A" (d) );
        return d;
}

int main()
{
        long long res;
        int a = 1;
        int b = 3;
        int c = 0;
        res=tick();
        c = (a + b)*11000;
        res=tick()-res;
        printf("%lld\n",res);
        return 0;
}

我的处理器配置如下。

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    2
Core(s) per socket:    4
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 30
Stepping:              5
CPU MHz:               1197.000
BogoMIPS:              5862.24
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0-7

从输出看,处理器看起来像是1.2GHz,据我所知,这意味着每秒会有1200 x 10 ^ 6个刻度。

当我在我的机器上运行时,上述程序的输出是完整的88.令人惊讶的是,即使我删除了&#39; c =(a + b)* 11000;&#39;从两个滴答之间仍然输出为88。

1)为什么输出没有增加(根据执行上述语句所需的周期,它应该略高一些。)

2)上面cpuinfo中列出的任何其他参数是否会影响CPU MHz以外的其他参数。

1 个答案:

答案 0 :(得分:2)

在X86_64上使用rdtsc时出现错误。 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=21249

tick()必须更正如下:

static inline unsigned long long tick()
{

    unsigned long low, high;
    __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high));
    return ((unsigned long long)high << 32) | low);


}