Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c timeval vs timespec

Tags:

c

linux

time

Apart from the difference of precision, what are the differences between struct timeval and struct timespec? If I need less precision than µs (say, milliseconds), why would I use one over the other?

On my compiler (gcc for ARM):

/* POSIX.1b structure for a time value.  This is like a `struct timeval' but
   has nanoseconds instead of microseconds.  */
struct timespec
  {
    __time_t tv_sec;        /* Seconds.  */
    __syscall_slong_t tv_nsec;  /* Nanoseconds.  */
  };

/* A time value that is accurate to the nearest
   microsecond but also has a range of years.  */
struct timeval
  {
    __time_t tv_sec;        /* Seconds.  */
    __suseconds_t tv_usec;  /* Microseconds.  */
  };

With both __syscall_slong_t and __suseconds_t defined as a "long word".

like image 582
Julien-L Avatar asked Jul 07 '15 17:07

Julien-L


People also ask

What is Timespec in C?

The structure timespec is defined in the time. h library of C and is used to store data such as time-elapsed. It allows the user to store time in seconds and nanoseconds.

What is Time_t structure?

Data Type: time_t. time_t is the simplest data type used to represent simple calendar time. In ISO C, time_t can be either an integer or a floating-point type, and the meaning of time_t values is not specified.

What is Tv_usec?

long int tv_sec. This represents the number of whole seconds of elapsed time. long int tv_usec. This is the rest of the elapsed time (a fraction of a second), represented as the number of microseconds.


1 Answers

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.)

like image 129
lyngvi Avatar answered Sep 21 '22 08:09

lyngvi