The clock_gettime
function requires a struct timespec
object as an argument.
https://linux.die.net/man/3/clock_gettime
In the date and time utilities section of the C standard library, there is a function difftime
which calculates the difference in two time_t
objects.
https://en.cppreference.com/w/c/chrono
However there does not appear to be an equivalent function for struct timespec
data.
I guess it is trivial to write one given that there are just two fields inside of a struct timespec
(one for the number of seconds and one for the number of nanoseconds). However, it seems surprising that the standard library does not include this function for convenience.
Here is an example of how to do it:
(time_stop.tv_sec - time_start.tv_sec)
+ 1.0e-9 * (time_stop.tv_nsec - time_start.tv_nsec);
Does a function to find the difference in time between two struct timespec
objects exist? Or is it perhaps not included because clock_gettime
can be called with different arguments for different types of clock?
struct timespec
(and the olderstruct timeval
— it'd be nice to have a set of those, too) are not always so trivial to write. I wish there were a standard set, too. I suspect the reason is that C has never sought to be voluminous or complete in that sort of way. – Doublegangertimespec_diff
function would not be sufficient, or would need an extraflags
argument or something. If you implemented theCLOCK_UTC
clock described at cl.cam.ac.uk/~mgk25/posix-clocks.html, you'd want a way to take differences between two of those values that either did or didn't honor leap seconds, or that returned an error if the computation were impossible due to leapsecond ambiguity or lack of sufficient leapsecond information. – Doubleganger