本文主要是介绍Linux 获取微秒级时间的函数 gettimeofday,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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
3. 运行效果
这篇关于Linux 获取微秒级时间的函数 gettimeofday的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!