高精度计时器QueryPerformanceCounter正确的打开方式(windows环

目前多核的CPU已经飞入寻常百姓人家,,因而作为开发人员,不得不面对在多核CPU的机器上使用QueryPerformanceCounter的情况。当我们需要在某一进程中获取时间,需要将该线程绑定在某一固定的核心上,这样获取的高精度计时器才是可靠的。通过SetThreadAffinityMask可以实现这一目的。举个栗子:HANDLE thread = GetCurrentThread();// Set affinity to the first coreDWORD_PTR oldMask = SetThreadAffinityMask(thread, GTimerMask );// Query the timerQueryPerformanceCounter(&mStartTime);mStartTick = GetTickCount();// Reset affinitySetThreadAffinityMask(thread, oldMask);使用前,需要重置GTimerMask:void appResetTimerMask(){// Get the current process core maskULONG_PTR proMask;ULONG_PTR sysMask;GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);// If procMask is 0, consider there is only one core available// (using 0 as procMask will cause an infinite loop below)if (procMask == 0)procMask = 1;// Find the lowest core that this process usesif (GTimerMask == 0){GTimeMask = 1;while ((GTimerMask & procMask) == 0){GTimerMask <<= 1;}}}完整的使用方法:inline DOUBLE appSeconds(){LARGE_INTEGER Cycles;HANDLE thread = NULL;ULONG_PTR oldMask = 0;if (GEnableTimerAffinityMask)//GEnableTimerAffinityMask为TRUE时需要将线程绑定到固定核心{thread = GetCurrentThread();if (GTimerMask == 0)//GTimerMask默认值为0{appResetTimerMask();}oldMask = SetThreadAffinityMask(thread, GTimerMask);}QueryPerformanceCounter(&Cycles);if (GEnableTimerAffinityMask){SetThreadAffinityMask(thread, oldMask);}return Cycles.QuadPart * GSecondsPerCycle + 16777216.0;}参考资料:https://msdn.microsoft.com/en-us/library/ee417693%28v=vs.85%29.aspx

我的眼泪流了下来,浇灌了下面柔软的小草,

高精度计时器QueryPerformanceCounter正确的打开方式(windows环

相关文章:

你感兴趣的文章:

标签云: