How to detect rdtscp support in Visual C++?

2019-08-10 06:54发布

问题:

I have a piece of code running on MSVC 2012:

#include <windows.h>
#include <intrin.h> 

UINT64 gettime() {
 try {
     unsigned int ui;
     return __rdtscp(&ui);
 }
 catch (...) {
     return __rdtsc();
 }
}

I was trying to use __rdtscp() to get the timestamp; however, on the platform where the __rdtscp() is not supported, I want to switch to __rdtsc() instead.

The above code doesn't work; the program simply crashed if the __rdtscp() is not supported (on certain VMs). So is there any way I can detect if the __rdtscp() is supported, but without crashing the program?

回答1:

From MSDN for rdtscp:

To determine hardware support for this instruction, call the __cpuid intrinsic with InfoType=0x80000001 and check bit 27 of CPUInfo[3] (EDX). This bit is 1 if the instruction is supported, and 0 otherwise.