timespec 在 tv_nsec 字段中可以有超过 1 秒的纳秒值吗?

标签 c linux time

我正在使用 clock_gettime() 命令并尝试将给定的毫秒数附加到我从中获取的 timespec。我可以这样做吗?

//milli is an int that can be any number (within reason)
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_nesc += (milli*1000000);

或者我是否需要将它拆分并首先找出是否有任何整秒,将它们添加到 tv_sec 字段,然后将剩余的添加到 tv_nsec?

本质上,tv_nsec 字段是否可以存储超过 1 秒的纳秒?

最佳答案

这完全取决于您要用它做什么。

struct timespectv_nsec 成员是long 类型。您可以将其设置为 LONG_MINLONG_MAX 范围内的任何值。如果您执行的计算超过 LONG_MAX,至少为 231-1,那么您将遇到问题(未定义的行为可能 显示为环绕的值)。

将其设置为小于 0 或大于或等于 10 亿的值是否会导致问题取决于您如何处理它。如果您只想打印它,或对其执行一些计算,任何有效的 long 值都应该没问题——但如果您将它们标准化,存储的值可能更有用。

clock_gettime() 应该始终为您提供 0..999999999 范围内的 tv_nsec 值。

POSIX 要求clock_settime()clock_nanosleep()nanosleep() 函数失败,并设置errnoEINVAL,如果“tp 参数指定了一个小于零或大于或等于 10 亿的纳秒值。”

引用资料:

http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_settime.html http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_nanosleep.html http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

关于timespec 在 tv_nsec 字段中可以有超过 1 秒的纳秒值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17114385/

相关文章:

c - 求五次多项式一次根的代码

c# - 在C#中将AM/PM时间转换为标准时间格式hh:mm

time - hive 将 PHT 时间转换为 UTC

java - 向时钟添加时间(不起作用)-JAVA

c - sqlite c api插入绑定(bind)

c - 无法连接两个字符串并从函数返回它

c - 我的函数中省略了参数名称

Java没有接受环境变量

python - vscode python linux : changes in debug console doesn't appear in 'variables->locals' debug pane

php - 使用 php 或 ruby​​ 在 linux 中操作 word 文档(doc、docx 等)