linux时间函数毫秒,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函数声明在头文件中。

下面举个例子:

#include

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能得到两个时间戳之间相隔了多少微秒。最后将结果输出。