2013 09 30 22 26 [程式] 使用 RDTSCP 來測量 performance

最近發現有新的指令 rdtscp 可以用來得到Time Stamp Counter,
而且不需要自行用cpuid來解決同步問題.
而windows visutal C++有直接提供 __rdtscp function來使用,
這邊我們只需要用同樣的interface寫一份給gcc使用.
範例如下:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#ifdef __GNUC__
static inline uint64_t __rdtscp(unsigned int *aux)
{
uint32_t low, high;
asm volatile(".byte 0x0f,0x01,0xf9"
            : "=a" (low), "=d" (high), "=c" (*aux));
return low | ((uint64_t)high << 32);
}
#else
#include <intrin.h>
#endif

int main()
{
  uint64_t t;
  uint32_t aux;

  t=__rdtscp(&aux);

  printf("t=%lld aux=%d\n",t,aux);

  return 0;
}

update: 2021/3/30

static inline uint64_t rdtscp()
{
    uint64_t rax,rdx;
    asm volatile ( "rdtscp\n" : "=a" (rax), "=d" (rdx) : : "%ecx" );
    return (rdx << 32) + rax;
}