1

我有这个代码

#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?

4

1 回答 1

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");
}
于 2015-04-02T09:15:46.327 回答