在Unix/Linux系統下,使用gettimeofday函數來獲得當前系統的時間戳,精度可達到微秒(microsecond,即μs)級別。
通過結構體timeval來存放當前時間戳的信息:
#ifndef _STRUCT_TIMEVAL #define _STRUCT_TIMEVAL struct timeval _STRUCT_TIMEVAL { __darwin_time_t tv_sec; /* seconds */ __darwin_suseconds_t tv_usec; /* and microseconds */ }; #endif /* _STRUCT_TIMEVAL */
其中,tv_sec用於存放當前時間戳的秒數,一般為long類型;tv_usec用於存放當前時間戳的微秒數,一般為int類型。
而這個結構體以及gettimeofday函數聲明在<sys/time.h>頭文件中。
下面舉個例子:
#include <sys/time.h> int main(void) { struct timeval tBegin, tEnd; gettimeofday(&tBegin, NULL); int count = 0; for(int i = 0; i < 1000 * 1000; i++) count += i; gettimeofday(&tEnd, NULL); long deltaTime = 1000000L * (tEnd.tv_sec - tBegin.tv_sec ) + (tEnd.tv_usec - tBegin.tv_usec); printf("Time spent: %ldus\n", deltaTime); }
上述代碼中,gettimeofday(&tBegin, NULL)用於獲得計算之前的時間戳;而gettimeofday(&tEnd, NULL)則用於獲得計算之后的時間戳。然后deltaTime能得到兩個時間戳之間相隔了多少微秒。最后將結果輸出。
順帶一提。在Windows系統下獲取毫秒級的時間戳函數為:GetTickCount(),只需要包含<windows.h>即可。返回類型為DWORD,表示從系統啟動后過去的毫秒數。