除了精度的差异,struct timeval和之间有什么区别struct timespec?如果我需要的精度低于μs(比如毫秒),为什么我要使用一个而不是另一个?
在我的编译器(ARM的gcc)上:
/* POSIX.1b structure for a time value. This is like a `struct timeval' but
has nanoseconds instead of microseconds. */
struct timespec
{
__time_t tv_sec; /* Seconds. */
__syscall_slong_t tv_nsec; /* Nanoseconds. */
};
/* 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. */
};
Run Code Online (Sandbox Code Playgroud)
随着双方__syscall_slong_t并__suseconds_t定义为"长字".
lyn*_*gvi 16
我认为这只是API [in]兼容性的问题.POSIX-y调用like pselect()和clock_gettime()use struct timespec.各种文件系统调用utimes(),以及一些类似gettimeofday()和select()使用的Linux调用struct timeval.从一些手册页大致概括,我怀疑它struct timeval有一个BSD遗产,而struct timespecPOSIX.
如果您正在进行间隔测量,则没有理由不利用额外的精度clock_gettime()- 尽管要注意它通常是硬件,而不是头文件,这会限制您的测量精度.为显示目的除以一百万不是更好或更差,而不是一千.此外,Mac OS X不支持clock_gettime().
但是如果你正在进行大量的文件时间操作,那么使用struct timeval像API这样的API 会更有意义utimes().struct timeval在Linux,BSD和Mac OS X上也有一些比较功能,例如timercmp(),timersub()(参见手册页).
我会根据您打算使用的API做出决定,而不是根据结构本身做出决定.(或者,如果需要,可以使用转换方法编写包装类.)