为什么rdtscp不返回核心ID?

时间:2014-06-30 11:16:55

标签: c++ linux rdtsc

我有这段代码

#include <iostream>
#include <sched.h>

unsigned long long rdtscp(unsigned int* aux)
{
    // For IA32
    unsigned long long x;
    asm volatile("rdtscp" : "=c" (*aux), "=A" (x) ::);
    return x;
}

int main()
{
  unsigned int  aux0, aux1 = -1, aux2;
  aux0 = sched_getcpu();
  unsigned long long x = rdtscp(&aux1);
  aux2 = sched_getcpu();
  std::cout << "aux0 = " << aux0 << ", aux1 = " << aux1 << ", aux2 = " << aux2 << ", x = " << x << std::endl;
  return 0;
}

它定义了一个函数rdtscp,它使用内联汇编来调用rdtscp汇编指令。 TSC值看起来很好但核心id始终为零,即使sched_getcpu()都返回了正确的核心ID而且它不为零。输出看起来像

# g++ test.cpp -o test ; ./test
aux0 = 2, aux1 = 0, aux2 = 2, x = 231368797247511

如何使用rdtscp获取TSC和核心ID?

1 个答案:

答案 0 :(得分:1)

您的硬件可能不支持 rdtscp 指令。你可能会检查一下:

#include <cpuid.h>
#include <stdio.h>

main()
{
    unsigned a, b, c, d;
    if (__get_cpuid(0x80000001, &a, &b, &c, &d))
        puts("unsupported instruction rdtscp" + (d&1<<27 ? 2 : 0));
    else
        puts("unsupported cpuid level");
}