struct timeval结构体 以及 gettimeofday()函数(转)

struct timeval结构体

转载地址:http://blog.chinaunix.net/uid-20548989-id-2533161.html

该结构体是Linux系统中定义,struct timeval结构体在time.h中的定义为:

1 struct timeval 
2 { 
3   __time_t tv_sec; /* Seconds. */ 
4   __suseconds_t tv_usec; /* Microseconds. */ 
5 }; 

其中,tv_sec为Epoch到创建struct timeval时的秒数,tv_usec为微秒数,即秒后面的零头。比如当前我写博文时的tv_sec为1244770435,tv_usec为442388,即当前时间距Epoch时间1244770435秒,442388微秒。需要注意的是,因为循环过程,新建结构体变量等过程需消耗部分时间,我们作下面的运算时会得到如下结果:

#include <sys/time.h> 
#include <stdio.h> 

int main(void) {
    int i; 
    struct timeval tv; 
    for(i = 0; i < 4; i++){ 
    gettimeofday(&tv, NULL); 
    printf("%d	%d
", tv.tv_usec, tv.tv_sec); 
    sleep(1); 
    }
    return 0; 
}

结果如下:

329612 1314851429
329782 1314851430
329911 1314851431
330036 1314851432

原文地址:https://www.cnblogs.com/jikexianfeng/p/6357294.html