---
name: "TIMESPEC_TO_TIMEVAL"
section: "3bsd"
platform: "linux"
package: "libbsd-dev"
version: "0.11.7-2"
release: "Debian 12 (Bookworm)"
platforms: ["linux"]
url: "https://new.carta.tech/timeval/3bsd"
---

# TIMESPEC\_TO\_TIMEVAL(3bsd)

time structures

Part of [timeval(3bsd)](/timeval/3bsd.md).

## NAME

**timeval**, **timespec** – time structures

## LIBRARY

library “libbsd”

## SYNOPSIS

**#include \<sys/time.h\>**

(See [libbsd(7)](/libbsd/7.md) for include usage.)

*void*\

**TIMEVAL\_TO\_TIMESPEC**(*struct timeval \*tv*, *struct timespec \*ts*);

*void*\

**TIMESPEC\_TO\_TIMEVAL**(*struct timeval \*tv*, *struct timespec \*ts*);

## DESCRIPTION

The ⟨sys/time.h⟩ header, included by ⟨time.h⟩, defines various structures related to time and timers.

1. The following structure is used by [gettimeofday(2)](/gettimeofday/2.md), 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.

2. The following structure is used by [nanosleep(2)](/nanosleep/2.md), 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 **TIMEVAL\_TO\_TIMESPEC**() and **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\_gettime(2)](/clock_gettime/2.md).

## SEE ALSO

[timeradd(3bsd)](/timeradd/3bsd.md)
