2013-08-19 124 views
1

我已經寫了一個非常簡單的C程序,試圖理解C(Linux)中的rdtsc。該程序如下。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.令人驚訝的是即使我刪除'c =(a + b)* 11000'從兩個刻度之間仍然輸出爲88

1)爲什麼輸出不增加。(它應該顯示略高基礎上執行他上面的語句花費的循環。)

2)有任何影響上面cpuinfo中列出的其他參數會影響CPU MHz以外的其他參數。

+2

我猜你的優化編譯器發出的表達無碼'C =(A + B)* 11000;'因爲它可以看到結果不會在任何地方使用。你看過你的編譯器生成的程序集嗎? – Blastfurnace

+2

嘗試將a,b和c聲明爲volatile –

回答

2

在X86_64上使用rdtsc時有一個錯誤。 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=21249

打勾()必須correctd如下:

static inline unsigned long long tick() 
{ 

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


}