clock_getres(2)

๐Ÿ‘‘ clock_getres โ€” clock and time functions โœจ

okay bestie, buckle UP, because this is the clock_getres(2) page, aka the System Calls Manual entry for the trio of functions that literally keep time on your machine. you're gonna learn about clocks, precision, and why CLOCK_REALTIME is complicated. let's go ๐Ÿ’…


๐ŸŒธ NAME

clock_getres, clock_gettime, clock_settime โ€” clock and time functions


๐Ÿ’– LIBRARY

Standard C library (libc, -lc), since glibc 2.17

Before glibc 2.17, it was the Real-time library (librt, -lrt)

ngl bestie if you're linking this on an ancient glibc you gotta add -lrt. that's the whole tea. ๐Ÿซ–

๐Ÿฆ‹ SYNOPSIS

#include <time.h>

int clock_getres(clockid_t clockid, struct timespec *_Nullable res);

int clock_gettime(clockid_t clockid, struct timespec *tp);
int clock_settime(clockid_t clockid, const struct timespec *tp);

โœจ Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

clock_getres(), clock_gettime(), clock_settime():
    _POSIX_C_SOURCE >= 199309L

๐ŸŒˆ DESCRIPTION

so, clock_getres() finds the resolution (precision) of whatever clock you point it at with clockid, and โ€” if res is not NULL โ€” it stores that resolution in the struct timespec that res points to. ๐Ÿ’ซ

here's the thing tho: the resolution of clocks depends on the implementation and cannot be configured by a particular process. like, it is what it is. ๐Ÿ™ˆ and if the time value that tp points to in a call to clock_settime() isn't a multiple of res, then it gets truncated to a multiple of res. yeah. it just gets chopped. ๐Ÿ’€

clock_gettime() and clock_settime() retrieve and set the time of the clock you specified in clockid.

the res and tp arguments are timespec(3) structures.

clockid is the identifier of the particular clock you're acting on. a clock may be system-wide and hence visible for all processes, or per-process if it measures time only within a single process. ๐ŸŽ€

every implementation supports the system-wide real-time clock, identified by CLOCK_REALTIME. its time represents seconds and nanoseconds since the Epoch. when its time gets changed, timers for a relative interval are unaffected, but timers for an absolute point in time are affected.

more clocks may be implemented. the interpretation of the corresponding time values and the effect on timers is unspecified. (read: don't @ me, POSIX said so.)

sufficiently recent versions of glibc and the Linux kernel support the following clocks:

  • CLOCK_REALTIME โ€” a settable system-wide clock that measures real (i.e., wall-clock) time. setting this clock requires appropriate privileges. this clock is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), and by frequency adjustments performed by NTP and similar applications via adjtime(3), adjtimex(2), clock_adjtime(2), and ntp_adjtime(3). this clock normally counts the number of seconds since 1970-01-01 00:00:00 Coordinated Universal Time (UTC) except that it ignores leap seconds โ€” near a leap second it's typically adjusted by NTP to stay roughly in sync with UTC. ๐Ÿ‘€
  • CLOCK_REALTIME_ALARM (since Linux 3.0; Linux-specific) โ€” like CLOCK_REALTIME, but settable only indirectly by setting CLOCK_REALTIME, and it behaves differently if the system is suspended. see timer_create(2).
  • CLOCK_REALTIME_COARSE (since Linux 2.6.32; Linux-specific) โ€” a faster but less precise version of CLOCK_REALTIME. it's settable only indirectly by setting CLOCK_REALTIME. use it when you need very fast, but not fine-grained timestamps. requires per-architecture support, and probably also architecture support for this flag in the vdso(7). โšก
  • CLOCK_TAI (since Linux 3.10; Linux-specific) โ€” a system-wide clock derived from wall-clock time but counting leap seconds. this clock does not experience clock adjustments caused by inserting leap seconds the way CLOCK_REALTIME does. it counts seconds since 1970-01-01 00:00 TAI (1969-12-31 23:59:50 UTC), so its epoch is ten seconds before CLOCK_REALTIME's. however, its implementation requires help from NTP, and if that help isn't available it behaves like CLOCK_REALTIME instead. ๐Ÿ˜ญ

its relationship to CLOCK_REALTIME for timestamps before 1972 is only approximate, as the leap second regime was introduced on 1972-01-01. because leap seconds are planned to be discontinued, its value from now on will likely remain exactly 37 seconds greater than CLOCK_REALTIME's for many years, after which its offset from CLOCK_REALTIME's will likely be adjusted by some other mechanism as yet unspecified. it is settable only indirectly by setting CLOCK_REALTIME.

the acronym TAI stands for the French "temps atomique international", or International Atomic Time. ๐Ÿ‡ซ๐Ÿ‡ทโœจ

  • CLOCK_MONOTONIC โ€” a nonsettable system-wide clock that represents monotonic time since โ€” as described by POSIX โ€” "some unspecified point in the past". on Linux, that point corresponds to the number of seconds that the system has been running since it was booted.

the CLOCK_MONOTONIC clock is not affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), but it is affected by frequency adjustments. this clock does not count time that the system is suspended. all CLOCK_MONOTONIC variants guarantee that the time returned by consecutive calls will not go backwards, but successive calls may โ€” depending on the architecture โ€” return identical (not-increased) time values. ๐Ÿ•ฐ๏ธ

  • CLOCK_MONOTONIC_COARSE (since Linux 2.6.32; Linux-specific) โ€” a faster but less precise version of CLOCK_MONOTONIC. use when you need very fast, but not fine-grained timestamps. requires per-architecture support, and probably also architecture support for this flag in the vdso(7).
  • CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific) โ€” similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to frequency adjustments. this clock does not count time that the system is suspended.
  • CLOCK_BOOTTIME (since Linux 2.6.39; Linux-specific) โ€” a nonsettable system-wide clock that is identical to CLOCK_MONOTONIC, except that it also includes any time that the system is suspended. this lets applications get a suspend-aware monotonic clock without having to deal with the complications of CLOCK_REALTIME, which may have discontinuities if the time is changed using settimeofday(2) or similar. ๐Ÿ’ค
  • CLOCK_BOOTTIME_ALARM (since Linux 3.0; Linux-specific) โ€” like CLOCK_BOOTTIME, but behaves differently if the system is suspended. see timer_create(2).
  • CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12) โ€” this clock measures CPU time consumed by this process (i.e., CPU time consumed by all threads in the process). on Linux, this clock is not settable.
  • CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12) โ€” this clock measures CPU time consumed by this thread. on Linux, this clock is not settable. ๐Ÿงต

Linux also implements dynamic clock instances as described below. ๐Ÿ‘‡

๐Ÿ”ฅ Dynamic clocks

in addition to the hard-coded System-V style clock IDs described above, Linux also supports POSIX clock operations on certain character devices. such devices are called "dynamic" clocks, and are supported since Linux 2.6.39.

using the appropriate macros, open file descriptors may be converted into clock IDs and passed to clock_gettime(), clock_settime(), and clock_adjtime(2). the following example shows how to convert a file descriptor into a dynamic clock ID. ๐ŸŽ€

#define CLOCKFD 3
#define FD_TO_CLOCKID(fd)   ((~(clockid_t) (fd) << 3) | CLOCKFD)
#define CLOCKID_TO_FD(clk)  ((unsigned int) ~((clk) >> 3))

struct timespec ts;
clockid_t clkid;
int fd;

fd = open("/dev/ptp0", O_RDWR);
clkid = FD_TO_CLOCKID(fd);
clock_gettime(clkid, &ts);

โญ RETURN VALUE

clock_gettime(), clock_settime(), and clock_getres() return 0 for success. on error, -1 is returned and errno is set to indicate the error.


๐Ÿ’€ ERRORS

  • EACCES โ€” clock_settime() does not have write permission for the dynamic POSIX clock device indicated.
  • EFAULT โ€” tp points outside the accessible address space.
  • EINVAL โ€” the clockid specified is invalid for one of two reasons. either the System-V style hard coded positive value is out of range, or the dynamic clock ID does not refer to a valid instance of a clock object.
  • EINVAL (clock_settime()): tp.tv_sec is negative or tp.tv_nsec is outside the range [0, 999,999,999].
  • EINVAL โ€” the clockid specified in a call to clock_settime() is not a settable clock.
  • EINVAL (since Linux 4.3) โ€” a call to clock_settime() with a clockid of CLOCK_REALTIME attempted to set the time to a value less than the current value of the CLOCK_MONOTONIC clock.
  • ENODEV โ€” the hot-pluggable device (like USB for example) represented by a dynamic clk_id has disappeared after its character device was opened. ๐Ÿ”Œ
  • ENOTSUP โ€” the operation is not supported by the dynamic POSIX clock device specified.
  • EOVERFLOW โ€” the timestamp would not fit in time_t range. this can happen if an executable with 32-bit time_t is run on a 64-bit kernel when the time is 2038-01-19 03:14:08 UTC or later. however, when the system time is out of time_t range in other situations, the behavior is undefined. ๐Ÿ˜ญ (yeah. undefined. no promises.)
  • EPERM โ€” clock_settime() does not have permission to set the clock indicated.

๐Ÿงš ATTRIBUTES

for an explanation of the terms used in this section, see attributes(7).

  • clock_getres(), clock_gettime(), clock_settime() โ€” Thread safety โ€” MT-Safe ๐Ÿ‘‘

so yeah, these are safe to call from multiple threads, periodt. ๐Ÿ’…


๐Ÿ•ฐ๏ธ VERSIONS ๐Ÿ’…

okay so POSIX.1 has some opinions, and here's what it says:

Setting the value of the CLOCK_REALTIME clock via clock_settime() shall have no effect on threads that are blocked waiting for a relative time service based upon this clock, including the nanosleep() function; nor on the expiration of relative timers based upon this clock. Consequently, these time services shall expire when the requested relative interval elapses, independently of the new or old value of the clock.

translation bestie: you can yank CLOCK_REALTIME around all you want and the sleepy threads / relative timers literally do not care, they still wake up when their own interval is up. iconic behavior honestly ๐Ÿ’…

And POSIX.1-2001 said a process with "appropriate privileges" could set CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID with clock_settime(). On Linux?? nope. Those clocks are not settable โ€” literally no process has "appropriate privileges". she said no ๐Ÿ˜Œ

๐Ÿฆ‹ C library/kernel differences โœจ

On some architectures, an implementation of clock_gettime() is provided in the vdso(7). sneaky lil speed boost, love that for us ๐Ÿซถ


๐Ÿ“œ STANDARDS ๐ŸŒˆ

POSIX.1-2024. that's the one, bestie ๐Ÿ“Œ


๐Ÿ‘‘ HISTORY ๐Ÿ’–

POSIX.1-1996, and then Linux 2.6. the origin story fr fr โœจ

On POSIX systems where these functions exist, the symbol _POSIX_TIMERS is defined in <unistd.h> to a value greater than 0. And POSIX.1-2008 makes these functions mandatory โ€” no more optional era, she's required now ๐Ÿ’…

The symbols _POSIX_MONOTONIC_CLOCK, _POSIX_CPUTIME, _POSIX_THREAD_CPUTIME are the little green flags telling you that CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, and CLOCK_THREAD_CPUTIME_ID are available. (peep sysconf(3) for more ๐Ÿ‘€)

POSIX.1-2024 made CLOCK_MONOTONIC mandatory too. queen got promoted ๐Ÿ‘‘

๐Ÿงš Historical note for SMP systems (the lore) ๐Ÿ˜ญ

Before Linux had kernel support for CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID, glibc was out here implementing these clocks on many platforms using timer registers straight from the CPUs (TSC on i386, AR.ITC on Itanium). And likeโ€ฆ those registers can differ between CPUs, so if a process got migrated to another CPU, these clocks could return bogus results. not the vibe ๐Ÿ˜ญ

If the CPUs in an SMP system have different clock sources, there is no way to maintain a correlation between the timer registers, because each CPU runs at a slightly different frequency. In that case clock_getcpuclockid(0) will return ENOENT to signify this condition. And then those two clocks are only useful if you can guarantee a process stays pinned to a certain CPU. commitment issues, honestly ๐Ÿ’€

Also the processors in an SMP system don't all start at exactly the same time, so the timer registers are typically running at an offset. Some architectures include code that tries to limit these offsets on bootup โ€” but that code cannot guarantee to accurately tune the offsets. glibc contains no provisions to deal with these offsets (unlike the Linux Kernel). Typically these offsets are small, so the effects may be negligible in most cases. tiny offset, tiny problem, we move ๐Ÿ’…

Since glibc 2.4, the wrapper functions for the system calls described in this page dodge all the above drama by employing the kernel implementation of CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID, on systems that provide such an implementation (i.e., Linux 2.6.12 and later). glow up complete ๐Ÿฆ‹


๐ŸŽ€ EXAMPLES โœจ

okay so the program below shows off clock_gettime() and clock_getres() with various clocks. and here's an example of what we might see when running the program ๐Ÿ‘€

$ ./clock_times x;
CLOCK_REALTIME : 1585985459.446 (18356 days +  7h 30m 59s)
     resolution:          0.000000001
CLOCK_TAI      : 1585985496.447 (18356 days +  7h 31m 36s)
     resolution:          0.000000001
CLOCK_MONOTONIC:      52395.722 (14h 33m 15s)
     resolution:          0.000000001
CLOCK_BOOTTIME :      72691.019 (20h 11m 31s)
     resolution:          0.000000001

๐Ÿ’œ Program source ๐ŸŒธ

/* clock_times.c

   Licensed under GNU General Public License v2 or later.
*/
#define _XOPEN_SOURCE 600
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>

#define SECS_IN_DAY (24 * 60 * 60)

static void
displayClock(clockid_t clock, const char *name, bool showRes)
{
    long             days;
    struct timespec  ts;

    if (clock_gettime(clock, &ts) == -1) {
        perror("clock_gettime");
        exit(EXIT_FAILURE);
    }

    printf("%-15s: %10jd.%03ld (", name,
           (intmax_t) ts.tv_sec, ts.tv_nsec / 1000000);

    days = ts.tv_sec / SECS_IN_DAY;
    if (days > 0)
        printf("%ld days + ", days);

    printf("%2dh %2dm %2ds",
           (int) (ts.tv_sec % SECS_IN_DAY) / 3600,
           (int) (ts.tv_sec % 3600) / 60,
           (int) ts.tv_sec % 60);
    printf(")\n");

    if (clock_getres(clock, &ts) == -1) {
        perror("clock_getres");
        exit(EXIT_FAILURE);
    }

    if (showRes)
        printf("     resolution: %10jd.%09ld\n",
               (intmax_t) ts.tv_sec, ts.tv_nsec);
}

int
main(int argc, char *[])
{
    bool showRes = argc > 1;

    displayClock(CLOCK_REALTIME, "CLOCK_REALTIME", showRes);
#ifdef CLOCK_TAI
    displayClock(CLOCK_TAI, "CLOCK_TAI", showRes);
#endif
    displayClock(CLOCK_MONOTONIC, "CLOCK_MONOTONIC", showRes);
#ifdef CLOCK_BOOTTIME
    displayClock(CLOCK_BOOTTIME, "CLOCK_BOOTTIME", showRes);
#endif
    exit(EXIT_SUCCESS);
}

๐Ÿ‘€ SEE ALSO ๐Ÿซถ


and that's the whole page bestie!! you made it to the end, consider yourself certified in clock lore ๐Ÿ•ฐ๏ธโœจ

this lil beauty comes from the Linux man-pages 6.20 collection, dated 2026-03-07, under the name clock_getres(2). go read it again when you forget, i know you will ๐Ÿ’… mwah, bye!! ๐Ÿ’–๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: Linux-man-pages-copyleft
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms