如何在GCC x86中用RDTSC计算时钟周期? [英] How to count clock cycles with RDTSC in GCC x86?

查看:194
本文介绍了如何在GCC x86中用RDTSC计算时钟周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Visual Studio,我可以从处理器读取时钟周期数,如下所示。
如何使用GCC做同样的事情?

  #ifdef _MSC_VER //编译器:Microsoft Visual Studio 

#ifdef _M_IX86 //处理器:x86

内嵌uint64_t clockCycleCount()
{
uint64_t c;
__asm {
cpuid //序列化处理器
rdtsc //读取时间戳记计数器
mov dword ptr [c + 0],eax
mov dword ptr [c + 4],edx
}
return c;


#elif defined(_M_X64)// Processor:x64

externCunsigned __int64 __rdtsc();
#pragma intrinsic(__ rdtsc)
inline uint64_t clockCycleCount()
{
return __rdtsc();
}

#endif

#endif




如果您真的想要调用RDTSC,您可以使用以下内联汇编:

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)); ((unsigned long long)lo)|(((unsigned long long)hi)<32;
return
}

#endif


With Visual Studio I can read the clock cycle count from the processor as shown below. How do I do the same thing with 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

解决方案

On recent versions of Linux gettimeofday will incorporate nanosecond timings.

If you really want to call RDTSC you can use the following inline assembly:

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

这篇关于如何在GCC x86中用RDTSC计算时钟周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆