[TOC]

概述

struct timeval结构体在time.h中的定义为:

1
struct timeval { time_t tv_sec; /* Seconds. */ suseconds_t tv_usec; /* Microseconds. */ }; 

其中,tv_sec为Epoch到创建struct timeval时的秒数,tv_usec为微秒。

struct timeval结构体在time.h中的定义为:

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

其中,tv_sec为Epoch到创建struct timeval时的秒数,tv_usec为微秒数,即秒后面的零头。比如当前我写博文时的tv_sec为1244770435,tv_usec为442388,即当前时间距Epoch时间1244770435秒,442388微秒。

1
2
3
4
5
6
7
8
9
10
11
12
int i;
for (i = 0; i < 4; ++i)
{
gettimeofday(&tv, NULL);
printf("%d\t%d\n", tv.tv_usec, tv.tv_sec);
sleep(1);
}

442388 1244770435
443119 1244770436
443543 1244770437
444153 1244770438

gettimeofday

获取当前时间(保存在结构体timeval中)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

int main(int argc, char * argv[]){

struct timeval tv; //(1)
while(1){
gettimeofday(&tv, NULL); //(2)
printf("time %u:%u\n", tv.tv_sec, tv.tv_usec);
sleep(2);
}
return 0;
}