Often I have to manage the time on my embedded systems, in POSIX Operating Systems I can ask to the OS the time using the gettimeofday() function.

 

The gettimeofday() function shall obtain the current time, expressed as seconds and microseconds since the Epoch, and store it in the timeval structure pointed to by tp. The resolution of the system clock is unspecified.

 

It is often necessary to subtract two values of type struct timeval or struct timespec. Here is the best way to do this. It works even on some peculiar operating systems where the tv_sec member has an unsigned type.

 

real-time-search

In my application I use the following code to subtract two timeval structs. (the original is here)

 

 

 1 /* Subtract the `struct timeval' values X and Y,
 2    storing the result in RESULT.
 3    Return 1 if the difference is negative, otherwise 0. */
 4 
 5 int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
 6 {
 7     /* Perform the carry for the later subtraction by updating y. */
 8     if (x->tv_usec < y->tv_usec)
 9     {
10         int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
11         y->tv_usec -= 1000000 * nsec;
12         y->tv_sec += nsec;
13     }
14     if (x->tv_usec - y->tv_usec > 1000000)
15     {
16         int nsec = (x->tv_usec - y->tv_usec) / 1000000;
17         y->tv_usec += 1000000 * nsec;
18         y->tv_sec -= nsec;
19     }
20 
21     /* Compute the time remaining to wait. tv_usec is certainly positive. */
22     result->tv_sec = x->tv_sec - y->tv_sec;
23     result->tv_usec = x->tv_usec - y->tv_usec;
24 
25     /* Return 1 if result is negative. */
26     return x->tv_sec < y->tv_sec;
27 }
28 

Gg1