| TIMEVAL(3) | Library Functions Manual | TIMEVAL(3) | 
timeval, timespec,
  itimerval, itimerspec,
  bintime —
#include <sys/time.h>
void
  
  TIMEVAL_TO_TIMESPEC(struct
    timeval *tv, struct
    timespec *ts);
void
  
  TIMESPEC_TO_TIMEVAL(struct
    timeval *tv, struct
    timespec *ts);
<sys/time.h> header,
  included by <time.h>, defines
  various structures related to time and timers.
struct timeval {
	time_t		tv_sec;
	suseconds_t	tv_usec;
};
    
    The tv_sec member represents the elapsed time, in whole seconds. The tv_usec member captures rest of the elapsed time, represented as the number of microseconds.
struct timespec {
	time_t		tv_sec;
	long		tv_nsec;
};
    
    The tv_sec member is again the elapsed time in whole seconds. The tv_nsec member represents the rest of the elapsed time in nanoseconds.
A microsecond is equal to one millionth of a second, 1000
        nanoseconds, or 1/1000 milliseconds. To ease the conversions, the macros
        TIMEVAL_TO_TIMESPEC() and
        TIMESPEC_TO_TIMEVAL() can be used to convert
        between struct timeval and struct
        timespec.
struct itimerval {
	struct timeval	it_interval;
	struct timeval	it_value;
};
    
    
struct itimerspec {
	struct timespec	it_interval;
	struct timespec	it_value;
};
    
    Both struct itimerval and struct itimerspec are used to specify when a timer expires. Generally, it_interval specifies the period between successive timer expirations. A value zero implies that the alarm will fire only once. If it_value is non-zero, it indicates the time left to the next timer expiration. A value zero implies that the timer is disabled.
struct bintime {
	time_t		sec;
	uint64_t	frac;
};
    
    The sec member specifies the time in seconds and frac represents a 64-bit fraction of seconds. The struct bintime is meant to be used in the kernel only. It is further described in timecounter(9).
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;
}
A better alternative would use the more precise clock_gettime(2).
| April 12, 2011 | NetBSD 9.3 |