timeval(3bsd)

πŸ“¦
version 0.12.1 Β· 2 versions
, in debian bookworm, opensuse-leap 16.0, ubuntu noble

πŸ’– timeval(3bsd) β€” bestie edition πŸ’–

okay so you found your way to timeval(3bsd) and honestly? iconic. this is a LOCAL manual page, and we're about to get into time structures together. grab a snack πŸ“


✨ NAME ✨

timeval, timespec β€” the time structures, babe. that's the whole vibe.


🌸 LIBRARY 🌸

utility functions from BSD systems β€” that's libbsd, and you link it with -lbsd. periodt.


πŸŽ€ SYNOPSIS πŸŽ€

#include <sys/time.h>

(and yeah β€” see libbsd(7) for how the include usage actually works, don't skip that part πŸ™ˆ)

void
TIMEVAL_TO_TIMESPEC(struct timeval *tv, struct timespec *ts);

void
TIMESPEC_TO_TIMEVAL(struct timeval *tv, struct timespec *ts);

πŸ¦‹ DESCRIPTION πŸ¦‹

so the <sys/time.h> header β€” which gets included by <time.h>, iykyk β€” defines a bunch of structures that are all about time and timers. two of them are the main characters here:

  1. first up, this one, and it's the one gettimeofday(2) uses, among others:
struct timeval {
        time_t          tv_sec;
        suseconds_t     tv_usec;
};

the tv_sec member is the elapsed time in whole seconds. and the tv_usec member catches the rest of the elapsed time β€” represented as the number of microseconds. so like, seconds + leftover micros = the whole moment. πŸ’«

  1. and then this one, which nanosleep(2) uses, among others:
struct timespec {
        time_t          tv_sec;
        long            tv_nsec;
};

tv_sec is again the elapsed time in whole seconds. and tv_nsec is the rest of the elapsed time, but this time in nanoseconds. same energy, finer resolution.

quick math check bestie, write this down: a microsecond is equal to one millionth of a second, 1000 nanoseconds, or 1/1000 milliseconds. and to make those conversions not be a whole struggle, the macros TIMEVAL_TO_TIMESPEC() and TIMESPEC_TO_TIMEVAL() exist to convert between struct timeval and struct timespec. slay. πŸ’…


πŸ”₯ EXAMPLES πŸ”₯

okay so it really can't be stressed enough that the traditional UNIX timeval and timespec structures represent elapsed time, measured by the system clock. so here's a little sketch that implements a function suitable for a context where the timespec structure is required for a conditional timeout:

static void
example(struct timespec *spec, time_t minutes)
{
        struct timeval elapsed;

        (void)gettimeofday(&elapsed, NULL);

        _DIAGASSERT(spec != NULL);
        TIMEVAL_TO_TIMESPEC(&elapsed, spec);

        /* Add the offset for timeout in minutes. */
        spec->tv_sec = spec->tv_sec + minutes * 60;
}

and ngl, a better alternative would use the more precise clock_gettime(2). just saying. πŸ‘‘


🌈 SEE ALSO 🌈


that's the whole page, you ate it πŸ’– this one comes from Debian, dated April 12, 2011 β€” yes she's an elder but she still serves. mwah, go write some code 🫢✨