補充:測配量序已耗用時間的幾種方法

來源:互聯網
上載者:User

     在從前寫的一篇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引起的常見錯誤.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.