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.
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
You might find `timersub` in `sys/time.h` useful.
Good suggestion!
I didn’t know about: timeradd, timersub, timercmp, timerclear, timerisset – timeval operations.
Since today, I will use these functions.
Anyway I come from realtime and embedded systems, and on some RTOS the above functions are not implemented.
Also, from the Linux man page:
Not in POSIX.1-2001. Present on most BSD derivatives.
from the freebsd man page:
The timeradd() family of macros were imported from NetBSD 1.1, and
appeared in FreeBSD 2.2.6.
So if you are using very old Linux/*bsd you should implements these functions.
And last, in windows/mingw, for that I know, there aren’t these functions.