c timeval vs timespec
I think it's really just a matter of API [in]compatibility. POSIX-y calls like pselect()
and clock_gettime()
use struct timespec
. Various filesystem calls like utimes()
, and some assorted Linux calls like gettimeofday()
and select()
, use struct timeval
. Broadly generalizing from a few man pages, I suspect that struct timeval
has a BSD legacy whereas struct timespec
is POSIX.
If you're doing interval measurements, there's no reason not to leverage the extra precision from clock_gettime()
— though beware that it's usually hardware, not the header file, that limits your measuring precision. Dividing by a million for display purposes is hardly better or worse than dividing by a thousand. Also, Mac OS X does not support clock_gettime()
.
But if you're doing lots of file time manipulation, it might make more sense to use the struct timeval
used in APIs like utimes()
. struct timeval
also has some comparison functions on Linux, BSD and Mac OS X, e.g. timercmp()
, timersub()
(again, see man pages).
I'd make the decision based on the APIs you intend to use, rather than on the structures themselves. (Or write a wrapper class with conversion methods if necessary.)
Both are AFAIK defined for POSIX.1-2001, so from a portability point of view, it doesn't matter which one you use. The most simple answer is: use whichever you need for the API you intend to call.
There COULD be a platform-dependent size benefit using struct timeval
:
The type suseconds_t shall be a signed integer type capable of storing values at least in the range [-1, 1000000].
in struct timespec
the second member is of type long
. An int
would be enough on a 32bit platform to fulfill the suseconds_t
requirements. But, on a 64bit system, time_t
is typically 64 bit, thus forcing the structure to pad to 16 bytes anyway. So a size benefit is -- improbable.
Personally, I use neither one. I prefer to express time as a simple int64_t
because that makes time calculations dead simple and if you have to, converting back to struct timeval
or struct timespec
is no problem either. Even if you want a precision of nanoseconds, int64_t
can express a span of almost 585 years. If you just need milliseconds, you have a span of almost 585 million years.