I noticed some programmers 开发者_如何学运维use unsigned long for tv_sec and tv_usec [when they copy them or operate with them] of timeval while they are defined as simply long.
Though it does make me wonder why they were defined like that when time usually goes forward.
Using long int
for those variables will work until year 2038, and after that the tv_sec
will overflow on machines where long
is 4bytes.
timeval shall be defined as:
The <sys/time.h> header shall define the timeval structure that includes at least the following members:
time_t tv_sec Seconds.
suseconds_t tv_usec Microseconds.
You should notice that time_t
type is used instead of long
, 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 the time_t
type instead, and you won't need to think about how long your program is supposed to run for in the future.
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
has type time_t
. tv_usec
has type long
, and needs to be signed because you will (on average 50% of the time) get negative results in tv_usec
when subtracting timeval
values to compute an interval of time, and you have to detect this and convert it to a borrow from the tv_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).
精彩评论