Linux中表示“时间”的结构体和相关函数

转:http://blog.chinaunix.net/uid-25909722-id-2827364.html

在Linux系统中,表示“时间”概念的结构体有多个,相关的时间处理函数也有很多,给人以很混乱的感觉。导致了当我们真正要使用这些结构体和函数的时候,却不知道到底该用哪个结构体和哪些函数。有必要加以归纳总结一下。通过查看头文件/usr/include/time.h 和 /usr/include/bits/time.h

(1)我们可以找到下列四种表示“时间”的结构体:
/* Returned by `time’. */
typedef __time_t time_t;

/* A time value that is accurate to the nearest
microsecond but also has a range of years. */
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};

struct timespec
{
__time_t tv_sec; /* Seconds. */
long int tv_nsec; /* Nanoseconds. */
};
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/

ifdef __USE_BSD

long int tm_gmtoff; /* Seconds east of UTC. */
__const char tm_zone; / Timezone abbreviation. */

else

long int __tm_gmtoff; /* Seconds east of UTC. */
__const char __tm_zone; / Timezone abbreviation. */

endif

};
其中:
time_t 是一个长整型,用来表示秒数。
struct timeval 结构体是用秒和微妙来表示时间。
struct timespec 结构体是用秒和纳秒来表示时间。
struct tm 直接用秒、分、小时、天、月、年等来表示时间。
很显然它们的精度是各不相同的。位各种不同的需要提供各种不同的选择。

(2)在Linux系统中我们如何获取当前的时间?

include

time_t time(time_t *t);
可以获取精确到秒的当前距离1970-01-01 00:00:00 +0000 (UTC)的秒数。

include

int gettimeofday(struct timeval *tv, struct timezone *tz);
可以获取精确到微秒当前距离1970-01-01 00:00:00 +0000 (UTC)的微秒数。

include

int clock_gettime(clockid_t clk_id, struct timespec *tp);
可以获取精确到纳秒当前距离1970-01-01 00:00:00 +0000 (UTC)的纳秒数。
例子:

include

include

include

include

include

include

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值