c++ - 如何在 GCC x86 中使用 RDTSC 计算时钟周期?

标签 c++ c gcc x86 rdtsc

使用 Visual Studio,我可以从处理器读取时钟周期计数,如下所示。 如何使用 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

最佳答案

其他答案有效,但您可以通过使用 GCC 的 __rdtsc 内在函数避免内联汇编,可通过包含 x86intrin.h 获得。

定义于:gcc/config/i386/ia32intrin.h :

/* rdtsc */
extern __inline unsigned long long
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
__rdtsc (void)
{
  return __builtin_ia32_rdtsc ();
}

关于c++ - 如何在 GCC x86 中使用 RDTSC 计算时钟周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887839/

相关文章:

c++ - ofstream 写入十六进制而不是 char*

c++ - 是否应该避免在 C/C++ 中使用递归调用?

c - 简单的 Makefile : undefined reference to symbol 'cos@@GLIBC_2.2.5' 问题

c - 轮询利用阻塞

linux - GCC 本地安装 Ubuntu

gcc - 以 "tree"开头的 gcc 标志有什么特别之处?

c++ - 使用其他类对象的数组类

c++ - 我可以在派生类中记录虚拟成员而不覆盖它吗?

c - C 中的隐式 "declaration-in-instantiation"?

c++ - 现在每个 Linux 发行版都附带 gcc/g++ 4.* 吗?