2012-03-27 8 views
10

Visual Studioでは、以下のようにプロセッサからのクロックサイクル数を読み取ることができます。 GCCで同じことをするにはどうしたらいいですか?クロックサイクル数wth GCC

#ifdef _MSC_VER    // Compiler: Microsoft Visual Studio 

    #ifdef _M_IX86      // Processor: x86 

     inline uint64_t clockCycleCount() 
     { 
      uint64_t c; 
      __asm { 
       cpuid  // serialize processor 
       rdtsc  // read time stamp counter 
       mov dword ptr [c + 0], eax 
       mov dword ptr [c + 4], edx 
      } 
      return c; 
     } 

    #elif defined(_M_X64)    // Processor: x64 

     extern "C" unsigned __int64 __rdtsc(); 
     #pragma intrinsic(__rdtsc) 
     inline uint64_t clockCycleCount() 
     { 
      return __rdtsc(); 
     } 

    #endif 

#endif 

答えて

15

Linuxの最近のバージョンでは、gettimeofdayにはナノ秒のタイミングが組み込まれます。

あなたは本当にあなたが以下のインラインアセンブリを使用することができますRDTSCを呼び出したい場合:私は、次を使用し、gccとLinuxの

http://www.mcs.anl.gov/~kazutomo/rdtsc.html

#if defined(__i386__) 

static __inline__ unsigned long long rdtsc(void) 
{ 
    unsigned long long int x; 
    __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x)); 
    return x; 
} 

#elif defined(__x86_64__) 

static __inline__ unsigned long long rdtsc(void) 
{ 
    unsigned hi, lo; 
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); 
    return ((unsigned long long)lo)|(((unsigned long long)hi)<<32); 
} 

#endif 
+1

はい、本当にRDTSCが必要ですが、今は持っています。ありがとうございました。 – user763305

+0

このコードにはシリアル化命令がないため、最新のプロセッサ(順序が間違っている)では間違った結果が得られます。通常はcpuidが使用されます。 – markhahn

+0

64ビットバージョンでは、gccでアセンブリが正しく生成されません。これを改善するには、 'rdx'を32ビット左にシフトするか、または' rax'を手動でシフトします。結果は 'rax'です。 –

5

を:

/* define this somewhere */ 
#ifdef __i386 
__inline__ uint64_t rdtsc() { 
    uint64_t x; 
    __asm__ volatile ("rdtsc" : "=A" (x)); 
    return x; 
} 
#elif __amd64 
__inline__ uint64_t rdtsc() { 
    uint64_t a, d; 
    __asm__ volatile ("rdtsc" : "=a" (a), "=d" (d)); 
    return (d<<32) | a; 
} 
#endif 

/* now, in your function, do the following */ 
uint64_t t; 
t = rdtsc(); 
// ... the stuff that you want to time ... 
t = rdtsc() - t; 
// t now contains the number of cycles elapsed 
19

他回答は機能しますが、GCCの__rdtsc組み込み関数を使用してインラインアセンブリを避けることができます。x86intrin.h

+0

この組み込み関数は、典型的には、署名「extern __inline unsigned long long __attribute __((__ gnu_inline__、__always_inline__、__artificial__)) __rdtsc(void)を持つため、効果はほとんど同じですが、読みやすくなります。 ) '、つまり結果として生成されたバイナリにインライン展開されます。 – Joost

関連する問題