1. 程式人生 > >【C&C++】查看代碼運行時間

【C&C++】查看代碼運行時間

was void sed aps ble item tor store number

  查看代碼運行時間有助於更好地優化項目代碼

1. Windows平臺

  windows平臺下有兩種方式,精度有所不同,都需要包含<windows.h>頭文件

1) DWORD GetTickCount(void); 返回毫秒數

  官方文檔:(3/28/2014) msdn

For Release configurations, this function returns the number of milliseconds since the device booted, excluding any time that the system was suspended. GetTickCount

starts at zero on boot and then counts up from there.

For debug configurations, 180 seconds is subtracted from the the number of milliseconds since the device booted. This enables code that uses GetTickCount to be easily tested for correct overflow handling.

  該函數有幾點需要註意:

  a) The elapsed time is stored as a DWORD

value. Therefore, the time will rollover to zero if the system is run continuously for 49.7 days

  b) For debug configurations, 180 seconds is subtracted from the the number of milliseconds since the device booted.

  c) On the STMicro platform, the time returned by GetTickCount includes a ~0.014% time drift, which is by design. This translates to a time lag of approximately 1 second    every 2 hours.

  d) 實際使用中,發現該函數相當不精確,對於運行時間只有10毫秒以內的代碼段,經常顯示0,百度百科中有講到這個函數並非實時發送,而是由系統每18ms發送一次,因此其最小精度為18ms。當需要有小於18ms的精度計算時,應使用StopWatch或其它方法進行。連續觸發200次,實測下來,最小間隔在15ms。實際狀況應該是系統每秒觸發64次,間隔在15、16ms之間波動。

2) BOOL WINAPI QueryPerformanceCounter( _Out_ LARGE_INTEGER *lpPerformanceCount); 返回微秒數

  官方文檔:msdn

  Retrieves the current value of the performance counter, which is a high resolution (<1us) time stamp that can be used for time-interval measurements.  

  

  

【C&C++】查看代碼運行時間