liveBook · Manning

Struct timespec

As explained in Modern C, Third Edition

struct timespec is a C structure type representing a time value with seconds and a nanosecond component.

struct timespec represents a time value by combining whole seconds with a nanosecond component. It uses the opaque time_t type for seconds and long for nanoseconds, preserving more precision than time_t alone. section 6.3.2 section 8.6

struct timespec {
  time_t tv_sec; // Whole seconds  ≥ 0
  long  tv_nsec; // Nanoseconds    [0, 999999999]
};

The declaration makes the representation and stated value ranges explicit: tv_sec stores whole seconds, while tv_nsec stores nanoseconds from 0 through 999999999. section 6.3.2

Use timespec_get to obtain a struct timespec value. The required TIME_UTC base is expected to agree with time; timespec_getres, added in C23, can query clock resolution. A difference operation between two struct timespec values can be implemented without platform-specific properties. section 6.3.2 section 8.6

TAKEAWAY:

  • Choose struct timespec when second-level time_t precision is insufficient. section 8.6
  • Treat tv_sec and tv_nsec as distinct components of one time value. section 6.3.2

How Modern C, Third Edition covers it

How deep it goes
Defines the two fields and their value ranges, then connects the type to acquisition, resolution, and difference operations.
Examples
Uses a declaration listing tv_sec and tv_nsec, plus timespec_get and timespec_getres function prototypes.
What it assumes
Assumes familiarity with C structures and time_t while explaining the seconds-and-nanoseconds representation.
What you can do after
Apply it via timespec_get to obtain nanosecond-precision time values and implement portable differences between them.
How it connects
Connects time_t, time, timespec_get, timespec_getres, TIME_UTC, and clock resolution.

Also explained in

Compare how 2 books explain struct timespec →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.