问题是这样的:我想在基于IOCTL示例框架的内核模式WDM驱动程序中计算CPU频率,但如果尝试使用QueryPerformanceFrequency或QueryPerformanceCounter,则不希望进行编译。 我觉得也许是因为它的内核模式驱动程序,它不会让我包含Windows.h,其中包含这些方法 – 它迫使我使用Ntddk.h来代替 。
通常我会在Win32控制台应用程序中使用这个函数来计算这个信息,但是它不准确,因为它并不考虑Intel CPU上的Turbo Boost:
float GetCoreFrequency() { // __rdtsc: Returns the processor time stamp which records the number of clock cycles since the last reset. // QueryPerformanceCounter: Returns a high resolution time stamp that can be used for time-interval measurements. // Get the frequency which defines the step size of the QueryPerformanceCounter method. LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); // Get the number of cycles before we start. ULONG cyclesBefore = __rdtsc(); // Get the start time. LARGE_INTEGER startTime; QueryPerformanceCounter(&startTime); ULONG cyclesAfter; LARGE_INTEGER endTime; // Get the number of cycles over some arbitrary but short enough period of time. do { cyclesAfter = __rdtsc(); QueryPerformanceCounter(&endTime); } while ((endTime.QuadPart - startTime.QuadPart) / frequency.QuadPart < 1); // Return the number of MHz. return (cyclesAfter - cyclesBefore)*pow(10, -6) / ((endTime.QuadPart - startTime.QuadPart) / frequency.QuadPart); }
英特尔芯片上的CPU频率的实际公式是最大频率乘以可从芯片本身的两个CPU寄存器(APERF和MPERF)获得的比率:
frequency = maximumFrequency * APERF / MPERF;
这转换成这个代码:
frequency = maximumFrequency * __readmsr(232) / __readmsr(231);
我希望能够从QueryPerformanceFrequency获得最高的频率,但是由于我无法将其纳入考虑,我怎样才能获得最高频率?