在基于linux的C编程中,经常会看到 struct timeval和struct timespec 这两个跟时间有关的结构体,有时候会容易混淆,先看下这两个结构体的定义,以linux-2.6.35为例,在time.h下
1 2 3 4 5 6 7 8 9 | struct timeval { __kernel_time_t tv_sec; /* seconds */ __kernel_suseconds_t tv_usec; /* microseconds */ }; struct timespec { __kernel_time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; |
进一步查找_kernel_time_t 的含义 可知这两个结构体的内容如下:
1 2 3 4 5 6 7 8 9 | struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ }; struct timespec { long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; |
小结:
1、struct timeval 的成员,一个是秒,一个是微秒,所以最高精度是 微秒。
2、struct timespec 的成员,一个是秒,一个是纳秒,所以最高精度是 纳秒。
常见应用场景:
1、struct timeval 一般由函数
1 | int gettimeofday(struct timeval *tv, struct timezone *tz) |
获取系统时间。
2、struct timespec 一般由函数
1 | int clock_gettime(clockid_t, struct timespec *) |
获取特定时钟的时间。