我正在使用该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);
Run Code Online (Sandbox Code Playgroud)
或者我是否需要将其拆分并找出是否有任何整秒,将其添加到tv_sec字段中,然后将剩余的添加到tv_nsec?
从本质上讲,该tv_nsec字段可以存储超过1秒的纳秒?
Kei*_*son 13
这完全取决于你将要用它做什么.
a的tv_nsec成员struct timespec是类型的long.你可以将其设置为你的范围喜欢的任何值LONG_MIN来LONG_MAX.如果您执行的计算超过LONG_MAX(至少为2 31 -1),那么您将遇到问题(未定义的行为可能会显示为值环绕).
无论是将其设置为小于0,还是大于或等于10亿,都会导致问题取决于您使用它做什么.如果您只是想打印它,或对它执行一些计算,任何有效值long都应该没问题 - 但是如果您将它们标准化,则存储的值可能更有用.
clock_gettime()应该总是给你一个tv_nsec0..999999999范围内的值.
POSIX要求clock_settime(),clock_nanosleep()和nanosleep()功能失效,并设置errno到EINVAL,如果"的TP参数指定的值纳秒小于零或者大于或等于1000万美元."
参考文献:
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 /功能/ nanosleep.html