(Linux)C语言中几个时间类型和函数

时间类型

在Linux C下,常用时间类型有四种:time_t、struct timeval、struct timespec、struct tm

time_t 类型

time_t类型是最基础的日历时间,表示从Linux Epoch(1970.01.01 00:00:00)到现在时刻的秒数,是一个长整型数。
time_t是在 time.h 中定义的:

/* Returned by `time'.  */
typedef __time_t time_t;

使用time()函数获取当前时间的time_t值,使用ctime()函数将time_t转为当地时间字符串。
使用difftime()函数可以计算两个time_t值的时间差。

struct timeval 类型

timeval 是一个常用的时间类型,它包含2个成员,一个是 tv_sec 是表示秒数,另一个是 tv_usec 微秒数(是一个小于1,000,000的整数),所以它表示时间的精度是到微秒。
timeval 是在 sys/time.h 中定义的:

struct timeval
  {
    __time_t tv_sec;›   ›   /* Seconds.  */
   __suseconds_t tv_usec;› /* Microseconds.  */
  };
 ```
 设置时间函数settimeofday( )与获取时间函数gettimeofday( )均使用该时间类型作为入参。
### struct timespec 类型
timespec 与 timeval 类似,不过它的精度更高,它包含2个成员,一个是 tv_sec ,另一个是 tv_nsec 纳秒(是一个小于1,000,000,000的长整型),过意它的时间精度是纳秒。timespec的纳秒也是目前日常编程中能获取到的精度最高的时间类型了。
timespec 是在 time.h 中定义的:
``` C
struct timespec
  {
    __time_t tv_sec;›   ›   /* Seconds.  */
    __syscall_slong_t tv_nsec;› /* Nanoseconds.  */
  };

struct tm 类型

tm 类型是一个表示分解时间( Broken-down Time)的时间类型,它将时间详细表示为年月日时分秒 he和 时区信息。
tm 是在 time.h 中定义的:

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
};

使用gmtime( )和localtime( )可将time_t时间类型转换为tm结构体;
使用mktime( )将tm结构体转换为time_t时间类型;
使用asctime( )将struct tm转换为字符串形式。

时间函数

Linux下常用时间函数有:time( )、ctime( )、gmtime( )、localtime( )、mktime( )、asctime( )、difftime( )、gettimeofday( )、settimeofday( )。上面略有提及,就不一一介绍了。

另外,对于timeval 或者 timespec 类型,计算两个时间差,可以自己写一下函数,如下演示了对timepec类型求差值:

int diff_timespec(struct timespec *result, struct timespec *begin, struct timespec *end)
{
    if(begin->tv_sec > end->tv_sec)
        return -1;
    if((begin->tv_sec == end->tv_sec) && (begin->tv_nsec > end->tv_nsec))
        return -2;
    result->tv_sec = (end->tv_sec - begin->tv_sec);
    result->tv_nsec = (end->tv_nsec - begin->tv_nsec);

    if(result->tv_nsec < 0)
    {
        result->tv_sec--;
        result->tv_nsec += 1000000000;
    }
    return 0;
}

(这里有点代码显示问题

参考文档:
https://www.gnu.org/software/libc/manual/html_node/Time-Types.html
https://en.cppreference.com/w/c/chrono/timespec
https://blog.csdn.net/water_cow/article/details/7521567

master

Stay hungry, stay foolish.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

*