我有这个代码
#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?