2008 03 18 16 08 在 gcc 下用 rdtsc


在gcc裡使用組語 rdtsc 來得到CPU的tick count。
所以需要在 C 中使用inline assembly,
但是gcc是用AT&T的組語格式。
如下:

#include <stdio.h>

#define rdtsc(low,high) __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
#define rdtscll(val) __asm__ __volatile__("rdtsc" : "=A" (val))

int main()
{
  int low[2],high[2];
  unsigned long long x;
  rdtsc(low[0],high[0]);
  rdtsc(low[1],high[1]);
  printf("%08x%08x\n",high[0],low[0]);
  printf("%08x%08x\n",high[1],low[1]);
  rdtscll(x);
  printf("%016llx\n",x);
  return 0;
}


參考:
http://en.wikipedia.org/wiki/RDTSC
GCC-Inline-Assembly-HOWTO
...