Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

timespec_get — retrieving time

timespec_get stores time in struct timespec. Check its return value before reading the fields; nanosecond representation does not guarantee nanosecond resolution.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <time.h>
int timespec_get(struct timespec *ts, int base);

timespec_get from <time.h> stores time in the object pointed to by ts. Pass the address of a writable struct timespec. Success returns base; failure returns 0, in which case do not read the fields.

For TIME_UTC, tv_sec holds seconds since an implementation-defined epoch, not necessarily the Unix epoch. tv_nsec holds nanoseconds rounded to the clock's resolution; the unit does not guarantee accuracy.

TIME_UTC does not guarantee monotonicity. C23 does not define TIME_MONOTONIC as a standard time base, even an optional one. An implementation may define additional time bases; their availability and behavior depend on the implementation.

Examples

#include <stdio.h>
#include <time.h>

int main(void)
{
    struct timespec ts;
    if (timespec_get(&ts, TIME_UTC) != TIME_UTC) {
        puts("unavailable");
        return 1;
    }
    puts(ts.tv_nsec >= 0 && ts.tv_nsec < 1000000000L
         ? "valid nanoseconds" : "invalid nanoseconds");
    return 0;
}

Result

valid nanoseconds

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources