Unix/Linux系统下获得时间戳函数

在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
", deltaTime);
}

上述代码中,gettimeofday(&tBegin, NULL)用于获得计算之前的时间戳;而gettimeofday(&tEnd, NULL)则用于获得计算之后的时间戳。然后deltaTime能得到两个时间戳之间相隔了多少微秒。最后将结果输出。


顺带一提。在Windows系统下获取毫秒级的时间戳函数为:GetTickCount(),只需要包含<windows.h>即可。返回类型为DWORD,表示从系统启动后过去的毫秒数。