在從前寫的一篇blog中,我介紹了測配量序已耗用時間的方法,其中在講到基於Timer的測量方法時,介紹了一個Win32函數QueryPerformanceCounter(),其實使用這種這個函數比起嵌入彙編的方法還是方便很多,但是也容易引起一些問題。下面是一段範例程式碼.
LARGE_INTEGER freq;
LARGE_INTEGER startTime, endTime;
LARGE_INTEGER elapsedTime, elapsedMilliseconds;
QueryPerformanceFrequency(&freq); //得到處理器的主頻
QueryPerformanceCounter(&startTime);
// 可以在這裡放置程式碼
QueryPerformanceCounter(&endTime);
elapsedTime = endTime - startTime;
elapsedMilliseconds = (1000 * elapsedTime) / freq;
但是隨著目前電腦多處理器並行計算的日漸普遍,這樣的方式有可能引起極大的錯誤,假如這樣的代碼:
QueryPerformanceCounter(&startTime);
QueryPerformanceCounter(&endTime);
在不同的處理器上執行,有可能是endTime在startTime執行之前完成,那麼這樣,最後計算的結果就會引起錯誤.
MSDN針對QueryPerformanceCounter也有以下一段解說文字:
On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function.
具體的做法在Game Timing and Multicore Processor這篇文章中有介紹,在該文章中,也建議不要使用RDTSC指令來擷取時間,當然考慮到相容性的需要,也提供了相應的工具修補這個問題.
P.S: 這裡有一個關於Timer的實作類別,處理了QueryPerformanceCounter引起的常見錯誤.