TIMEVAL_TO_TIMESPEC (3)
Leading comments
$NetBSD: timeval.3,v 1.12 2011/04/12 08:39:26 jruoho Exp $ Copyright (c) 2010 The NetBSD Foundation, Inc. All rights reserved. This code is derived from software contributed to The NetBSD Foundation by Jukka Ruohonen. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2....
NAME
timeval timespec - time structuresLIBRARY
Lb libbsdSYNOPSIS
In sys/time.h (See libbsd(7) for include usage.) Ft void Fn TIMEVAL_TO_TIMESPEC struct timeval *tv struct timespec *ts Ft void Fn TIMESPEC_TO_TIMEVAL struct timeval *tv struct timespec *tsDESCRIPTION
The In sys/time.h header, included by In time.h , defines various structures related to time and timers.-
The following structure is used by
gettimeofday(2),
among others:
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.
-
The following structure is used by
nanosleep(2),
among others:
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 Fn TIMEVAL_TO_TIMESPEC and Fn TIMESPEC_TO_TIMEVAL can be used to convert between struct timeval and struct timespec
EXAMPLES
It can be stressed that the traditional UNIX timeval and timespec structures represent elapsed time, measured by the system clock. The following sketch implements a function suitable for use in 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; }
A better alternative would use the more precise clock_gettime2.