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)