我有这个代码

#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值看起来不错,但是即使两个sched_getcpu()返回了正确的核心ID,核心ID始终为零,但它也不为零。输出看起来像
# g++ test.cpp -o test ; ./test
aux0 = 2, aux1 = 0, aux2 = 2, x = 231368797247511

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

最佳答案

您的硬件可能不支持 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");
}

关于c++ - 为什么rdtscp不返回核心ID?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24488918/

10-13 05:30