转: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]*/
long int tm_gmtoff; /* Seconds east of UTC. */ __const char tm_zone; / Timezone abbreviation. */
long int __tm_gmtoff; /* Seconds east of UTC. */ __const char __tm_zone; / Timezone abbreviation. */
}; 其中: time_t 是一个长整型,用来表示秒数。 struct timeval 结构体是用秒和微妙来表示时间。 struct timespec 结构体是用秒和纳秒来表示时间。 struct tm 直接用秒、分、小时、天、月、年等来表示时间。 很显然它们的精度是各不相同的。位各种不同的需要提供各种不同的选择。
(2)在Linux系统中我们如何获取当前的时间?
time_t time(time_t *t); 可以获取精确到秒的当前距离1970-01-01 00:00:00 +0000 (UTC)的秒数。
int gettimeofday(struct timeval *tv, struct timezone *tz); 可以获取精确到微秒当前距离1970-01-01 00:00:00 +0000 (UTC)的微秒数。
int clock_gettime(clockid_t clk_id, struct timespec *tp); 可以获取精确到纳秒当前距离1970-01-01 00:00:00 +0000 (UTC)的纳秒数。 例子:
新闻热点
疑难解答