clock_gettime() — Linux system interface
Read the selected clock into seconds and nanoseconds. CLOCK_REALTIME represents wall-clock time and can jump; CLOCK_MONOTONIC is nondecreasing and useful for elapsed intervals, but does not include system suspend on Linux. CLOCK_BOOTTIME includes suspend. CLOCK_PROCESS_CPUTIME_ID measures process CPU consumption. Check the return value and normalize differences when nanoseconds borrow across seconds. EINVAL can indicate an unsupported clock ID. On suitable systems libc may use the vDSO instead of entering the kernel. Do not infer precision from the nanosecond field. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <time.h>int clock_gettime(clockid_t clockid, struct timespec *tp);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| clockid | clockid_t | Selected clock. |
| tp | struct timespec * | Writable result storage. |
Return Value
0 on success. On failure, returns -1 and sets errno.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <time.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(void){ struct timespec a, b; CHECK(clock_gettime(CLOCK_MONOTONIC, &a) == 0); CHECK(clock_gettime(CLOCK_MONOTONIC, &b) == 0); CHECK(a.tv_nsec >= 0 && a.tv_nsec < 1000000000L); CHECK(b.tv_nsec >= 0 && b.tv_nsec < 1000000000L); CHECK(b.tv_sec > a.tv_sec || (b.tv_sec == a.tv_sec && b.tv_nsec >= a.tv_nsec)); puts("monotonic samples nondecreasing; nanoseconds normalized"); return EXIT_SUCCESS;}