1. 简介
一言以蔽之,返回本时区从 19700101 的 00:00开始,到本函数执行时的秒数和微秒数。
1970年到目前大约是54+年的时间。
声明:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
描述:
DESCRIPTION
The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone.
The tv argument is a struct timeval (as specified in <sys/time.h>):
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
and gives the number of seconds and microseconds since the Epoch (see time(2)).
The tz argument is a struct timezone:
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
RETURN VALUE
gettimeofday() and settimeofday() return 0 for success, or -1 for failure (in which case errno is set appropriately).
跟多内容:
$ man gettimeofday
2. 应用示例
这个示例将时间换算为了秒,也可以换算为微妙;
可以执行两次本函数,获得 time1 和 time2,获得两者之间经历的时间长度。
hello_get_time_of_day.cpp
#include <stdio.h>
#include <sys/time.h>
extern "C"
double get_seconds_from_19700101_time( void )
{
struct timeval t;
gettimeofday( &t, NULL );
return t.tv_sec + t.tv_usec*1e-6;
}
int main()
{
double x = 0.0;
x = get_seconds_from_19700101_time();
printf("\nx = %13.2f seconds\n = %13.2f days\n = %13.2f years\n\n", x, x/60.0/60.0/24.0, x/60.0/60.0/24.0/365.0);
return 0;
}
Makefile:
hello_get_time_of_day:
.PHONY: clean
clean:
-rm -rf hello_get_time_of_day