POSIX Clocks & High-Resolution Timers

The POSIX Time & Clock Specification (IEEE Std 1003.1, <time.h>) standardizes nanosecond-precision time measurement, monotonic clock domains, sleeping primitives, and asynchronous kernel interval timers.

In distributed systems, microsecond-budgeted networking, and event loops, choosing the wrong clock source can cause disastrous failure modes: negative time jumps during NTP synchronizations, frozen timeouts, or unexpected thread wakeups.

1. POSIX Clock Domains

POSIX replaces the legacy gettimeofday() API (which offered microsecond resolution and was tied strictly to system wall-clock time) with clock_gettime():

#include <time.h>

int clock_gettime(clockid_t clk_id, struct timespec *tp);
int clock_settime(clockid_t clk_id, const struct timespec *tp);
int clock_getres(clockid_t clk_id, struct timespec *res);

struct timespec {
    time_t tv_sec;   /* Seconds */
    long   tv_nsec;  /* Nanoseconds [0, 999999999] */
};

The Four Essential Clock Sources

┌────────────────────────────────────────────────────────┐
│                   CLOCK_REALTIME                       │
│    (Wall-Clock Time: Affected by NTP Slew/Step & User) │
└────────────────────────────────────────────────────────┘

┌────────────────────────────────────────────────────────┐
│                  CLOCK_MONOTONIC                       │
│     (Strictly Forward-Ticking: Immune to NTP Steps)    │
└────────────────────────────────────────────────────────┘

┌────────────────────────────────────────────────────────┐
│              CLOCK_PROCESS_CPUTIME_ID                  │
│       (Per-Process CPU Execution Cycles Consumed)      │
└────────────────────────────────────────────────────────┘

┌────────────────────────────────────────────────────────┐
│               CLOCK_THREAD_CPUTIME_ID                  │
│        (Per-Thread CPU Execution Cycles Consumed)      │
└────────────────────────────────────────────────────────┘
Clock ID Monotonic? Affected by NTP? Best Use Case
CLOCK_REALTIME ❌ No (Can jump backward!) Yes (Subject to manual set and NTP step/slew) Displaying calendar time, user-facing timestamps, SSL certificate expiration.
CLOCK_MONOTONIC ✅ Yes (Strictly monotonic) Frequency slew only; never jumps backward Measuring elapsed execution time, timeout calculations, rate limiting.
CLOCK_MONOTONIC_RAW (Linux) ✅ Yes ❌ No (Direct hardware tick counter without slew) Hardware-level latency benchmarking.
CLOCK_BOOTTIME (Linux) ✅ Yes Monotonic including system suspend/sleep state Network keepalives, IoT heartbeats.
CLOCK_PROCESS_CPUTIME_ID ✅ Yes N/A Profiling total CPU time consumed across all threads in process.
CLOCK_THREAD_CPUTIME_ID ✅ Yes N/A High-resolution per-thread profiling and CPU budgeting.

[!WARNING] Never use CLOCK_REALTIME for calculating timeouts or intervals. If system administrators or NTP daemons step the clock backward by a few seconds, an application waiting on a timeout calculated via CLOCK_REALTIME will hang or calculate negative elapsed durations. Always use CLOCK_MONOTONIC.

Measuring Microsecond Latency with CLOCK_MONOTONIC

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

uint64_t get_monotonic_nanos(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ((uint64_t)ts.tv_sec * 1000000000ULL) + (uint64_t)ts.tv_nsec;
}

void benchmark(void) {
    uint64_t start = get_monotonic_nanos();
    // Perform intensive task...
    uint64_t elapsed_ns = get_monotonic_nanos() - start;
    printf("Elapsed: %.2f microseconds\n", (double)elapsed_ns / 1000.0);
}

2. High-Resolution Sleeping: nanosleep() vs. clock_nanosleep()

Legacy sleep functions like sleep() (seconds) and usleep() (microseconds) interact poorly with POSIX signals (often implemented via SIGALRM), overriding process signal handlers and lacking interrupted-time recovery.

Standard nanosleep()

int nanosleep(const struct timespec *req, struct timespec *rem);
  • Suspends execution of the calling thread until the requested req time elapses or a signal interrupts the call.
  • If interrupted by an asynchronous signal handler, nanosleep() returns -1 with errno = EINTR and populates rem with the remaining unslept time, allowing clean restart loops.

Deterministic clock_nanosleep()

POSIX.1-2001 introduced clock_nanosleep() to enable sleeping against a designated clock domain:

int clock_nanosleep(clockid_t clock_id, int flags,
                    const struct timespec *request,
                    struct timespec *remain);

Passing TIMER_ABSTIME in flags allows sleeping until an absolute time point, rather than an interval. This completely eliminates timer drift across recurring periodic tasks:

// Periodic task executing precisely every 10 milliseconds without drift
struct timespec next_wake;
clock_gettime(CLOCK_MONOTONIC, &next_wake);

while (running) {
    // Add 10ms (10,000,000 ns)
    next_wake.tv_nsec += 10000000;
    if (next_wake.tv_nsec >= 1000000000) {
        next_wake.tv_sec += 1;
        next_wake.tv_nsec -= 1000000000;
    }

    // Sleep until absolute target time
    clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next_wake, NULL);

    execute_periodic_work();
}

3. Kernel Interval Timers: timer_create() and timer_settime()

Unlike BSD setitimer() (which only supports a single timer per process and delivers SIGALRM), POSIX interval timers allow a process to allocate multiple independent hardware timers:

#include <signal.h>
#include <time.h>

int timer_create(clockid_t clockid, struct sigevent *sevp, timer_t *timerid);
int timer_settime(timer_t timerid, int flags,
                  const struct itimerspec *new_value,
                  struct itimerspec *old_value);
int timer_delete(timer_t timerid);

Flexible Expiration Notifications (struct sigevent)

A POSIX timer can notify the application upon expiration via:

  1. SIGEV_SIGNAL: Delivers a specified POSIX signal (e.g., SIGRTMIN + 1) to the process with siginfo_t metadata.
  2. SIGEV_THREAD: Automatically invokes a C function in a new thread created by the C runtime library. This is ideal for worker pools and background health check loops without manual signal plumbing.
  3. SIGEV_NONE: Silently updates timer state without delivering interrupts (queried via timer_gettime()).

Setting Up a Background Thread Timer

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

void on_timer_expire(union sigval val) {
    printf("Timer expired! Iteration tag: %d\n", val.sival_int);
}

int main(void) {
    timer_t timer_id;
    struct sigevent sev = {0};

    sev.sigev_notify = SIGEV_THREAD;
    sev.sigev_notify_function = on_timer_expire;
    sev.sigev_value.sival_int = 42;

    timer_create(CLOCK_MONOTONIC, &sev, &timer_id);

    struct itimerspec its;
    // Initial expiration in 1 second
    its.it_value.tv_sec = 1;
    its.it_value.tv_nsec = 0;
    // Recurring interval every 500 milliseconds
    its.it_interval.tv_sec = 0;
    its.it_interval.tv_nsec = 500000000;

    timer_settime(timer_id, 0, &its, NULL);

    // Run for 3 seconds then cleanup
    sleep(3);
    timer_delete(timer_id);
    return 0;
}

Related Topics