gpt4 book ai didi

c timeval 与 timespec

转载 作者:IT王子 更新时间:2023-10-29 00:04:18 27 4
gpt4 key购买 nike

struct timevalstruct 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. */
};

__syscall_slong_t__suseconds_t 都定义为“长字”。

最佳答案

我认为这实际上只是 API [in] 兼容性的问题。 POSIX-y 调用类似 pselect()clock_gettime()使用 struct timespec。各种文件系统调用,如 utimes() ,以及一些类似 gettimeofday() 的 Linux 调用和 select() , 使用 struct timeval。从几个手册页中大致概括,我怀疑 struct timeval 具有 BSD 遗留而 struct timespec 是 POSIX。

如果您正在进行间隔测量,则没有理由不利用 clock_gettime() 的额外精度 — 尽管请注意通常是硬件而非头文件限制了您的测量精度。出于显示目的而除以一百万与除以一千相比几乎没有好坏之分。 (另外,Mac OS X prior to 10.12 did not support clock_gettime()。)

但如果您要进行大量文件时间操作,则使用 utimes() 等 API 中使用的 struct timeval 可能更有意义。 struct timeval 在 Linux、BSD 和 Mac OS X 上也有一些比较函数,例如timercmp()timersub()(再次参见手册页)。

我会根据您打算使用的 API 做出决定,而不是根据结构本身。 (或者在必要时编写一个带有转换方法的包装类。)

关于c timeval 与 timespec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275131/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com