对 timeval 成员使用 unsigned long 有好处吗?
我注意到一些程序员对 timeval 的 tv_sec 和 tv_usec [当他们复制它们或使用它们进行操作时]使用 unsigned long,而它们被定义为简单的 long。
尽管这确实让我想知道为什么当时间通常向前推进时它们会被这样定义。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对这些变量使用
long int
将一直有效到 2038 年以及之后tv_sec
在long
为 4 字节的机器上会溢出。timeval 应定义为:
您应该注意到<使用 code>time_t 类型代替
long
,但在某些系统上它也是 32 位表示,而在其他系统上甚至有 64 位表示。为了避免溢出,time_t
可能会更改为无符号32位整数或64位整数。这就是为什么有些人使用
unsigned long
,因为它会阻止溢出直到 2100 年以上。您应该使用time_t
类型,这样您就不需要考虑您的程序将来应该运行多长时间。Using
long int
for those variables will work until year 2038, and after that thetv_sec
will overflow on machines wherelong
is 4bytes.timeval shall be defined as:
You should notice that
time_t
type is used instead oflong
, but which is also a 32bit representation on some systems while there are even 64bit representations on other systems. In order to avoid overflow,time_t
will probably be changed to an unsigned 32bit integer or a 64bit one.That is why some are using
unsigned long
, as it will stop the overflow until year 2100+. You should use thetime_t
type instead, and you won't need to think about how long your program is supposed to run for in the future.当 Unix 时间被发明时,负时间可能是有意义的。例如,AT&T 需要足够的时间戳来记录 20 世纪 60 年代发生的事情。
至于微秒,如果减去两个值,则可以得到有符号值的负数,以及无符号值的 4+十亿。与0相比似乎更直观。
When unix time was invented, negative times probably made sense. Like, AT&T needed adequate timestamps for things that happened in the 1960s.
As for microseconds, if you subtract two values you can go into negative numbers with signed value, and into 4+billions with unsigned. Comparing with 0 seems more intuitive.
tv_sec
的类型为time_t
。tv_usec
的类型为long
,并且需要签名,因为在减法时您会(平均 50% 的时间)在tv_usec
中得到负结果timeval
值来计算时间间隔,您必须检测到这一点并将其转换为从tv_sec
字段借用的值。标准(POSIX)本来可以使类型无符号,并要求您提前检测包装,但它没有,可能是因为这会更难使用并且与现有实践相矛盾。从范围来看,
tv_usec
也没有理由是无符号的,因为它真正需要能够表示的最大范围是-999999到1999998(或者如果你想累积的话,可以是这个范围的几倍)重新规范化之前进行了几次加法/减法)。tv_sec
has typetime_t
.tv_usec
has typelong
, and needs to be signed because you will (on average 50% of the time) get negative results intv_usec
when subtractingtimeval
values to compute an interval of time, and you have to detect this and convert it to a borrow from thetv_sec
field. The standard (POSIX) could have instead made the type unsigned and required you to detect wrapping in advance, but it didn't, probably because that would be harder to use and contradict existing practice.There is also no reason, range-wise, for
tv_usec
to be unsigned, since the maximum range it really needs to be able to represent is -999999 to 1999998 (or several times that if you want to accumulate several additions/subtractions before renormalizing).