1. 函数功能:
gettimeofday是计算机函数,使用C语言编写程序需要获得当前精确时间(1970年1月1日到现在的时间),或者为执行计时,可以使用gettimeofday()函数。
2. 函数原型:
int gettimeofday(struct timeval *tv, struct timezone *tz);
3. 头文件:
#include <sys/time.h>
4.说明:
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
timezone 参数若不使用则传入NULL。
struct timeval {
time_t tv_sec; // seconds 秒
suseconds_t tv_usec; // microseconds 微秒
};
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich 格林威治时间往西方的时差 */
int tz_dsttime; /* type of DST correction 时间的修正方式*/
};
返回值:
gettimeofday() and settimeofday() return 0 for success, or -1 for failure
示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
/*
int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval {
time_t tv_sec; // seconds
suseconds_t tv_usec; // microseconds
};
*/
int get_time(struct timeval *tm)
{
int res;
res = gettimeofday(tm, NULL);
return res;
}
int main(int argc, char *argv[])
{
int ret=0;
struct timeval now;
while(1)
{
ret = get_time(&now);
if(ret) return -1;
printf("now_seconds=%ld,now_microseconds=%ld \n", now.tv_sec, now.tv_usec);
sleep(1);
}
return 0;
}
执行结果:
dawsen@KeVen:/mnt/m/work/time$ ./time
now_seconds=1526134532,now_microseconds=652143
now_seconds=1526134533,now_microseconds=653081
now_seconds=1526134534,now_microseconds=653895